How to save Chinese Characters to file with java?

前端 未结 6 1998
小蘑菇
小蘑菇 2020-12-13 22:10

I use the following code to save Chinese characters into a .txt file, but when I opened it with Wordpad, I couldn\'t read it.

StringBuffer Shanghai_StrBuf =          


        
6条回答
  •  孤城傲影
    2020-12-13 22:45

    Here's one way among many. Basically, we're just specifying that the conversion be done to UTF-8 before outputting bytes to the FileOutputStream:

    String FileName = "output.txt";
    
    StringBuffer Shanghai_StrBuf=new StringBuffer("\u4E0A\u6D77");
    boolean Append=true;
    
    Writer writer = new OutputStreamWriter(new FileOutputStream(FileName,Append), "UTF-8");
    writer.write(Shanghai_StrBuf.toString(), 0, Shanghai_StrBuf.length());
    writer.close();
    

    I manually verified this against the images at http://www.fileformat.info/info/unicode/char/ . In the future, please follow Java coding standards, including lower-case variable names. It improves readability.

提交回复
热议问题