我嘗試讀取「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