我尝试读取“bytefile”中的字节,将其更改为String并将其存储为“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^[email protected]<81>^B*É^X¿uú<9b>^@
在 “stringfile” 的模式是这样的:
�zg�oG^[email protected]�^B*�^X�u��^@�� V�
然而,在“newbytefile模式“是这样的:
[[email protected]
如何将“stringfile”中的字符串转换为与“bytefile”中的原始patten相同的字节?
如何将数组转换为字符串:http://stackoverflow.com/questions/409784/whats-the-simplest-way- to-print-a-java-array –
'writer.println(line.getBytes());'实际调用'println(Object)',然后调用'Object'的默认'toString'。 – Berger