我建议使用十六进制,它更加紧凑和可读
StringBuilder sb = new StringBuilder();
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream("1.txt"))) {
for (int b; (b = is.read()) != -1;) {
String s = Integer.toHexString(b).toUpperCase();
if (s.length() == 1) {
sb.append('0');
}
sb.append(s).append(' ');
}
}
System.out.println(sb);
输出
71 77 65 77 65 72 0D 0A 71 77 72 65 0D 0A 72 77 65 72 0D 0A
对于二进制字符串更改代码
String s = "0000000" + Integer.toBinaryString(b);
s = s.substring(s.length() - 8);
sb.append(s).append(' ');
并得到这个输出
01110001 01110111 01100101 01110111 01100101 01110010 00001101 00001010
这就是如何解析字符串并写回文件
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("2.txt"));
Scanner sc = new Scanner(s);
while (sc.hasNextInt()) {
int b = sc.nextInt(2);
out.write(b);
}
out.close();