从Java程序将Unicode字符打印到Windows 7控制台时,为什么还会显示其他字符?

时间:2019-02-27 09:29:10

标签: java windows unicode console character

下面是一个Java程序,用于向Windows控制台打印Unicode字符

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

public class PrintUnicodeChar {
  public static void main (String[] argv) throws UnsupportedEncodingException {
    String unicodeMessage = "\u00A3"; // Pound sign

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    out.print(unicodeMessage);
  }
}

我选择了Lucida Console作为字体,并将代码页设置为65001。

我得到的输出是£。

如果我使用"\u00A3\u00A3\u00A3"打印3次井号,则输出为£££££。打印具有更高unicode值的字符会输出更多-使其更乱码。

这里是另一个字符串"\u00A3\n\u00A3\u00A3\n\u00A3\u00A3\u00A3\n\u00A3\u00A3\u00A3\u00A3\n\u00A3\u00A3\u00A3\u00A3\u00A3\n"

输出为

£

££

£££

££££

£££££

�£

£££££

�££

发生了什么事? Windows 7终端是否有问题?如何防止其他字符打印?

1 个答案:

答案 0 :(得分:0)

您的代码没有错。

发生问题,因为Windows在控制台属性中不支持UTF-8 [python中类似的问题:How to display utf-8 in windows console]

您可以通过以下方式打印到文件来绕过此问题:

PrintStream out = new PrintStream(new FileOutputStream(fileDir), true, "UTF8");

完整代码:

public static void main(String[] args) throws IOException {
    String unicodeMessage = "\u00A3"; // Pound sign
    File fileDir = new File("c:\\temp\\test.txt");
    PrintStream out = new PrintStream(new FileOutputStream(fileDir), true, "UTF-8");
    out.print(unicodeMessage);
}

另一种解决方案:在Linux vm上的docker中运行代码(以避免与Windows相关的问题)