我在Java中的字符串中存储了字节
String header ="00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";
现在我想将该String写入文件,但将其导出为一系列位而不是作为文本编码。 写入文件如下所示:
BufferedWriter writer = new BufferedWriter (new FileWriter("test.epd"));
writer.write(header);
我该怎么做(这个编程中的字符串会更长 - >大约8kB)
答案 0 :(得分:1)
我会使用来自commons apache BinaryCodec的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);