【问题标题】:Java with maven, netbeansJava与maven,netbeans
【发布时间】:2021-07-09 03:00:37
【问题描述】:

我目前正在开发一个关于国际象棋的项目。主要思想是在控制台上将其用作 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... 

【问题讨论】:

    标签: java maven output


    【解决方案1】:

    它很复杂,非常复杂,它因操作系统而异,也因版本而异(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 的开头部分,或者尝试不同的控制台...这很复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 2016-01-12
      • 2016-11-17
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多