java - 将包含字节的字符串导出到文件而不进行编码

标签 java string byte

我在 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/

相关文章:

Java 字节和浮点乘法

java - 从特定位置检索属性文件

java - 我如何在java中递归地重新排列字符串

c# - 在数学回合中使用 'double' 中的逗号

c - 分割一个字符串并存储在数组的数组中

java - java中字节范围如何为-128到127。这怎么可能?

java - 无法使用 Spring Boot 将日期时间保存到 MongoDB

java - log4j:错误 "org.apache.log4j.ConsoleAppender"对象不可分配给 "org.apache.log4j.Appender"变量

java - JVM:是否可以操作帧堆栈?

java - 我的 int 的字节数