【发布时间】:2017-07-12 01:30:42
【问题描述】:
所以我有一个包含数千个 1 和 0 的字符串,我想将它们作为二进制文件保存到文件中(这样文件大小就很小)。不幸的是,如果不遇到 NumberFormatExceptions,我无法弄清楚如何做到这一点。
我已经尝试过 Byte.parseByte 但这似乎不起作用。任何帮助将不胜感激。
try {
File file = new File(BINARY_FILE);
DataOutputStream dso = new DataOutputStream(new FileOutputStream(file));
for (int j = 0; j < bits.length(); j += 8) {
Byte b = Byte.parseByte(bits.substring(j, j + 8));
dso.write(b);
}
} catch (IOException e) {
System.out.println("Error");
}
【问题讨论】:
-
显示你尝试过的代码
-
新增,bits变量为1和0的字符串。
-
另外,我们保证String的长度能被8整除吗?
-
不,我们不是,这确实会导致处理字符串中的最后一个字符出现问题。这就是为什么我希望有一种方法可以写出单个位。