Windows控制台中的西里尔文(java)System.out.println();

当我写一些西里尔文本,System.out.println(“Русскийязык”) – 然后它推出这个╨єёёъшщч√ъ,使用Windows控制台,怎么可以这个修复?,文件编码是utf-8,但它没关系,当它是ansii或windows-1251时,输出相同。

import java.io.PrintStream; class Kyrill { public static void main(String args[]) throws java.io.UnsupportedEncodingException { String ru = "Русский язык"; PrintStream ps = new PrintStream(System.out, true, "UTF-8"); System.out.println(ru.length()); System.out.println(ru); ps.println(ru); } } D:\Temp :: chcp 65001 Aktive Codepage: 65001. D:\Temp :: javac -encoding utf-8 Kyrill.java && java Kyrill 12 ??????? ???? Русский языкй язык 

请注意,您可能会在输出中看到一些尾随垃圾(我这样做),但是如果您将输出重定向到文件,您会发现这只是一个显示器。

因此,您可以使用PrintStream使其工作。 System.out使用平台编码(对我来说是cp1252),并且没有西里尔字符。

您需要了解编码业务的其他说明:

 D:\Temp :: chcp 1251 Aktive Codepage: 1251. :: This is another codepage (8 bits only) that maps bytes to cyrillic characters. :: Edit the source file to have: :: PrintStream ps = new PrintStream(System.out, true, "Windows-1251"); :: We intend to match the console output; else we won't get the expected result. D:\Temp :: javac -encoding utf-8 Kyrill.java && java Kyrill 12 ??????? ???? Русский язык 

所以你可以看到,与某些人认为的相反,Windows控制台在随意的意义上确实可以打印出希腊语和俄语。

虽然您可以通过chcp 65001将Windows控制台切换为UTF-8,但您仍可能无法正确查看UTF-8输出。 这可能不是您想要的,但它至少是一个选择:将标准输出重定向到文件。 将源文件保存为UTF-8并使用UTF-8编码进行编译。 可以使用支持UTF-8的文本编辑器查看重定向的输出文件。

 String s = "Русский язык"; System.setOut(new PrintStream(new FileOutputStream("out.txt"), true, "UTF-8")); System.out.println(s); 

由于历史原因,Windows控制台使用Cyrillic编码CP866(还记得DOS?)。 Windows控制台绝对不支持Unicode。

(唉,我没有Windows机器来提供经过测试的代码片段。)