Java 使用 maven、netbeans

Java with maven, netbeans

我目前正在开发一个关于国际象棋的项目。主要思想是在控制台上将其用作 CMD。 它目前与数组 [8][8] 一起使用,我将“棋子”存储在上面。但主要问题是: 当我想将表情符号打印为“♜、♞、♝ 等”时,输出将表情符号显示为 ?我已经尝试过一些东西,比如 UTF-8、Emoji-Java 库、 用兼容的字体更改输出控制台的字体...我已经尝试了几个小时,我在互联网上搜索过,我找不到任何东西...如果你能帮助我,我将不胜感激。

 [?][?][?][?][?][?][?][?]//♜, ♞, ♝, ♛, ♚, ♝, ♞, ♜.  
 [null][null][null][null][null][null][null][null]//Null= available space to move
 [null][null][null][null][null][null][null][null]
 [null][null][null][null][null][null][null][null]
 [null][null][null][null][null][null][null][null]
 [null][null][null][null][null][null][null][null]
 [null][null][null][null][null][null][null][null]
 [null][null][null][null][null][null][null][null]
//Please ignore the null values, it's going to be fixed when the problem is solved... 

它很复杂,非常复杂,它因OS而不同,它也因版本而异(windows 7 vs 10),它因补丁级别而异(例如windows 例如补丁2004之前和之后的10)。

因此,让我通过建议您使用 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 的步骤: Or for windows cmd you can take a look here: 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

并且输出应该给出以下结果:

Using UTF_8 output with the character: ♜

Using UTF_8 output with the unicode definition: ♜

但它可能仍然无法正确显示,在这种情况下,请参阅我关于使用 UI 的开头部分,或者尝试使用不同的控制台...这很复杂。