我的代码中有一个字符串,其中包含一堆 0 和 1。现在我想从这个字符串中创建一个文件,里面的位是这个字符串的字符。我该怎么做?
最佳答案
此函数会将二进制字符串解码为字节数组:
static byte[] decodeBinary(String s) {
if (s.length() % 8 != 0) throw new IllegalArgumentException(
"Binary data length must be multiple of 8");
byte[] data = new byte[s.length() / 8];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '1') {
data[i >> 3] |= 0x80 >> (i & 0x7);
} else if (c != '0') {
throw new IllegalArgumentException("Invalid char in binary string");
}
}
return data;
}
然后你可以用Files.write
将字节数组写入文件(或 OutputStream
):
String s = "0100100001100101011011000110110001101111"; // ASCII "Hello"
byte[] data = decodeBinary(s);
java.nio.file.Files.write(new File("file.txt").toPath(), data);
关于java - 将二进制文件从字符串写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668994/