将带字节的字符串导出到文件而不编码

时间:2014-10-21 16:22:59

标签: java string byte

我在Java中的字符串中存储了字节

String header ="00110011000000011001000000000001001011000000000100000010000000000000000000000000000000000000000000000000000000000000000000000000";

现在我想将该String写入文件,但将其导出为一系列位而不是作为文本编码。 写入文件如下所示:

BufferedWriter writer = new BufferedWriter (new FileWriter("test.epd"));
writer.write(header);

我该怎么做(这个编程中的字符串会更长 - >大约8kB)

1 个答案:

答案 0 :(得分:1)

我会使用来自commons apache BinaryCodeccommons-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);