How to save Chinese Characters to file with java?

前端 未结 6 1997
小蘑菇
小蘑菇 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:34

    If you can rely that the default character encoding is UTF-8 (or some other Unicode encoding), you may use the following:

        Writer w = new FileWriter("test.txt");
        w.append("上海");
        w.close();
    

    The safest way is to always explicitly specify the encoding:

        Writer w = new OutputStreamWriter(new FileOutputStream("test.txt"), "UTF-8");
        w.append("上海");
        w.close();
    

    P.S. You may use any Unicode characters in Java source code, even as method and variable names, if the -encoding parameter for javac is configured right. That makes the source code more readable than the escaped \uXXXX form.

提交回复
热议问题