它很复杂,非常复杂,它因操作系统而异,也因版本而异(windows 7 vs 10),并且因补丁级别而异(例如,windows 10 在补丁 2004 之前和之后)。
因此,让我建议您使用 UI 来代替您控制底层字符集,从而为您节省数小时的心痛。例如,使用 Swing 或 JavaFX。
但是,如果您坚持使用控制台,则需要采取一些步骤。
首先是在您的代码中使用PrintWriter 以使用正确的编码写出字符:
PrintWriter consoleOut = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
consoleOut.println("your character here");
下一步是预先配置控制台以使用您的字符集。例如,在 Windows 中,您可以在启动 jar 文件之前使用 chcp 命令:
chcp 65001
java -jar .....
但不仅如此,您应该在启动 jar 时使用 Dfile.encoding 标志:
java -Dfile.encoding=UTF-8 -jar yourChessApplciation.jar
现在假设您正确完成了所有这些步骤,它可能会起作用,但可能不会。您还需要确保所有源文件都以 UTF-8 编码。我不会在这里讨论,因为它与这个 IDE 不同,但如果你使用的是 Netbeans 之类的东西,那么你可以在项目属性中配置源编码。
我还鼓励您在代码中使用 Unicode 字符定义而不是实际符号:
//Avoid this, it may fail for a number of reasons (mostly encoding related)
consoleOut.println("♜");
//The better way to write the character using the unicode definition
consoleOut.println("\u265C");
现在,即使有了所有这些,您仍然需要确保您选择的控制台使用正确的字符集。以下是 powershell 的步骤:Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10) 或者对于 windows cmd,您可以在这里查看:How to make Unicode charset in cmd.exe by default
因此,完成所有这些步骤后,您就可以编译此代码了:
PrintWriter consoleOut = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8));
consoleOut.println("Using UTF_8 output with the character: ♜");
consoleOut.println("Using UTF_8 output with the unicode definition: \u265C");
consoleOut.close();
然后在控制台(本例中为 Powershell)中运行编译后的 jar 文件,如下所示(如果您正确配置了 powershell 控制台,则无需使用chcp 65001):
chcp 65001
java -Dfile.encoding=UTF-8 -jar yourChessApplciation.jar
并且输出应该给出以下结果:
使用带有字符的 UTF_8 输出:♜
使用带有 unicode 定义的 UTF_8 输出:♜
但它可能仍然无法正确显示,在这种情况下,请参阅我关于使用 UI 的开头部分,或者尝试不同的控制台...这很复杂。