JDK 21起全面利用UTF-8作为字符编码,带有汉字注释的源代码如果是ANSI格式,则编译会出错:
javac WriteFile.javaWriteFile.java:9: 缺点: 编码 UTF8 的不可映射字符 (0xC3) // ?????д??????????????GBK ^WriteFile.java:9: 缺点: 编码 UTF8 的不可映射字符 (0xFC) // ?????д??????????????GBK ^WriteFile.java:9: 缺点: 编码 UTF8 的不可映射字符 (0xC1) // ?????д??????????????GBK
办理办法:编译时选择指定字符编码为GBK
javac -encoding GBK WriteFile.java
或者利用文本编辑器程序将源文件另存为UTF-8格式保存后,直接编译也没有问题。

利用如下代码测试,直接输出汉字字符串常量没有问题,初步剖析该当是输入处理的问题。
FileWriter fw = new FileWriter(file);PrintWriter out = new PrintWriter(fw);out.println("测试汉字输出 by CHEN");
原来程序的键盘输入语句为:
String s;BufferedReader in = new BufferedReader(new InputStreamReader(System.in));while ((s = in.readLine()) != null) { out.println(s);}
输出的文件除了测试的内容汉字正常,其他键盘输入的内容乱码。剖析缘故原由该当是命令行窗口默认字符编码为GBK,为了避免乱码,须要在转换处理流这里指定字符集编码为GBK。
修正代码指定字符集GBK:
BufferedReader in = new BufferedReader( new InputStreamReader(System.in,"GBK"));
再次测试,文件内容可正常保存汉字。
附完全测试程序代码:
import java.io.;public class WriteFile { public static void main (String args[]) { // Create file File file = new File(args[0]); try { // 命令行窗口默认字符编码为GBK //为了避免乱码,须要在转换处理流这里指定字符集编码为GBK BufferedReader in = new BufferedReader( new InputStreamReader(System.in,"GBK")); //默认输出文件编码为UTF-8 FileWriter fw = new FileWriter(file); PrintWriter out = new PrintWriter(fw); out.println("测试汉字输出 by CHEN"); System.out.print("Enter file text. "); System.out.println("[Type cntl-z to stop.]"); String s;// Read each input line and echo it to the screen. while ((s = in.readLine()) != null) { out.println(s); } // Close the buffered reader and the file print writer. in.close(); out.close(); } catch (IOException e) { // Catch any IO exceptions. e.printStackTrace(); } }}