我尝试从“bytefile”读取字节,将其更改为字符串并将其存储到“stringfile”。下面的代码是我的执行方式。
PrintWriter writer = new PrintWriter(new FileOutputStream(new File("stringfile"), true));
RandomAccessFile file = new RandomAccessFile("bytefile", "r");
byte[] b = new byte[(int)file.length()];
file.readFully(b);
String str = new String(b, StandardCharsets.UTF_8);
writer.write(str);
writer.close();
然后我尝试将“stringfile”中的字符串转换为字节并存储在“newbytefile”中。然而结果并没有达到我的预期。
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("stringfile"), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream("newbytefile"), charset));
String line;
while ((line = reader.readLine()) != null){
writer.println(line.getBytes());
}
reader.close();
writer.close();
“bytefile”中的模式是这样的:
<9e>zgóoG^P$@0<81>^B*É^X¿uú<9b>^@
“stringfile”中的模式是这样的:
�zg�oG^P$@0�^B*�^X�u��^@�� V�
但是,“newbytefile”中的模式是这样的:
[B@40226788
如何将“stringfile”中的字符串转换为与“bytefile”中原始模式相同的字节?
最佳答案
问题是:PrintWriter 没有方法来写入 byte[] 数组。
因此,当您调用 println(getBytes())
时...编译器会尝试查找匹配的重载方法。它将找到 println(Object)
(因为:最终,任何 java 数组也是一个对象)。
你可以看到使用javap反汇编器:
invokevirtual #22 // Method java/io/PrintWriter.println:(Ljava/lang/Object;)V
在该方法中,对传入对象调用 toString()
。当您在字节数组上调用 toString() 时,您会得到类似于“[B....”的结果 - 请参阅 here为什么会这样。
换句话说:由于重载,您不会打印字节数组本身,而是打印该字节数组的默认字符串表示形式。
关于java - 将字节转换为字符串再转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43209833/