"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" のパターンは、このようなものです:
�zg�oG^[email protected]�^B*�^X�u��^@�� V�
しかし、「newbytefile内のパターン:
<9e>zgóoG^[email protected]<81>^B*É^X¿uú<9b>^@
"stringfile" のパターンは、このようなものです"は次のようなものです:
[[email protected]
"stringfile"の文字列を "bytefile"の元のpattenと同じバイトに変換するにはどうすればよいですか?
文字列に配列を変換する方法:あなたのバイト配列を適切に変換することができ、これは動作します提供
http://stackoverflow.com/questions/409784/whats-the-simplest-way- –
'writer.println(line.getBytes());'は実際に 'println(Object)'を呼び出し、次に 'Object'のデフォルトの' toString'を呼び出します。 – Berger