为什么有些 ASCII 和 Unicode 字符不能用 java 写入命令提示符?

Why some ASCII and Unicode characters cannot write to the command prompt with java?

我尝试用 java 编写一个主机纸牌游戏。而且我必须使用这些 ♥ ♦ ♣ ♠ 字符。但是当我在命令提示符下启动程序时,字符看起来像? ? ? ? .我尝试了 Unicode 和 ASCII,得到了相同的结果。我使用的是 intellij idea。我可以写这些 Ascii 字符 217┘ 218┌ 191┐ 192└ 196─

我试着把它们打印成

System.out.println("♥")

System.out.println(Character.toString('\u2661'))

Unicode 字符\u2661 ...等等。 ASCII 码 3 4 5 6

它适用于 Intellij Idea 终端。 当我尝试在命令提示符 alt+3 上手动写入时,我可以写入 ♥ 但在开始游戏时它看起来像 ?

here a png of my default encoding.xml

here output of Inellij console

and here output of cmd console

──────────────────────────────────────────── ──

编辑:

try {
        if (System.getProperty("os.name").contains("Windows")){
            new ProcessBuilder("cmd", "/c", "chcp 65001").inheritIO().start().waitFor();
        }
} catch (IOException | InterruptedException ex) {}

您真正需要粘贴的只是 System.out.println("♥"),其余的无关紧要。

您的问题中没有足够的信息来提供正确的答案。我认为是这三个之一:

[1] 您的文件采用某种字符集编码(例如 UTF-8),但是生成 class 文件的 javac 运行 配置了 -encoding ISO-8859-1 或其他内容否则那不是UTF-8。如果你让 intellij 为你编译它,我有点怀疑是不是它。

[2] 您正在 运行 进行此操作的控制台(也许是 intellij 的控制台视图)也有一个字符集编码,它不是 UTF_8.

[3] 它一直是 UTF-8,但是,用于呈现它的字体没有可用的符号。这也不太可能;渲染缺失字符的通常方法是一个盒子,或者一个里面有问号的菱形,而不是一个普通的 ?。或者你看到的是什么?

假设您正在尝试使用 System.out 进行打印,那么试试这个:

import java.io.PrintStream;
import static java.nio.charset.StandardCharsets.UTF_8;

public class App {

    public static void main(String[] args) {
        System.out.println("First attempt: ♣");
        PrintStream out = new PrintStream(System.out, true, UTF_8);
        out.println("Second attempt: ♣");
    }
}

在我的环境中,这将打印以下输出:

First attempt:  ?
Second attempt: ♣

在某些情况下,这可能仍然不够,具体取决于您 运行 您的代码。例如,如果您在 NetBeans 中 运行 它,则可能需要将以下内容添加到 Netbeans 启动选项中:

-Dfile.encoding=UTF-8