我在 Java 中的字符串中存储了字节
String header ="00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";
现在我想将该字符串写入文件,但将其导出为一系列位,而不是编码为文本。 写入文件如下所示:
BufferedWriter writer = new BufferedWriter (new FileWriter("test.epd"));
writer.write(header);
我该怎么做(这个程序中的字符串会更长-->大约8kB)
最佳答案
我会使用BinaryCodec来自 apache 公共(public)资源 commons-codec .
String headerb = "00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";
BinaryCodec codec = new BinaryCodec();
//I have no idea why this method is not static.
//you may use BinaryCodec.fromAscii(ascii.toCharArray()) instead
byte[] bval = codec.toByteArray(headerb);
File file = new File("test.epd");
Files.write(bval, file );
//Test that when the file is read, we retrieve the same string
byte[] byteArray = Files.toByteArray(file);
String asciiString = BinaryCodec.toAsciiString(byteArray);
System.out.println(asciiString);
关于java - 将包含字节的字符串导出到文件而不进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26491553/