java FileOutputStream Chinese disorderly code problem solution

  • 2020-06-19 10:18:17
  • OfStack

The solution of FileOutputStream Chinese garbled code in java

FileOutputStream serialization can be used to write text directly to the file, as follows:


FileOutputStream outStream = new FileOutputStream(file);
outStream.write(str.getBytes());
outStream.close();

This is because FileOutputStream is a byte stream that writes text to a file by byte, while a Chinese character is a two-byte stream that cannot be written once, resulting in a scrambled code. The solution is to use OutputStreamWriter to convert the byte stream to a character stream and specify the utf-8 encoding.

The code is as follows:


OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
oStreamWriter.append(str);
oStreamWriter.close();

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: