9

我想在 Windows 控制台中打印俄语和德语字符。所以我写了一个小测试程序来了解它的工作原理:

PrintStream ps = new PrintStream(System.out, false, "UTF-8");
ps.println("öäüß гджщ");

然后我启动了 cmd.exe,将其字体更改为支持 Unicode 的 Lucida Console,将代码页更改为带有“chcp 65001”的 Unicode 并执行我的程序。

打印了德语和俄语字符,但文本比我预期的要多一点(用红色下划线): 在此处输入图像描述

但是文本在 Eclipse 控制台中正确打印。有没有办法在 Windows 控制台中正确打印它?我使用 Windows 7。

我刚刚用 JNI 解决了这个问题,但是对于纯 java 是否可行仍然很有趣。

4

3 回答 3

1

每次打开或写入文件时,都会应用某种编码。但有时我们忘记了我们的 IDE(在您的情况下为 Eclipse)也有编码。

当您在引号之间键入某个文本时,它会以某种编码(即您的 IDE 的编码)显示和输入。您的假设是您的输出流(UTF-8)的编码也将保证文本以该特定编码显示。但是,我认为这里也再次应用了您的 IDE 的编码。

我建议仔细检查您对 eclipse 的编码。也许这可以解决您的问题。当然值得一试,不是吗?:)

对于全局编码设置,将以下代码添加到 eclipse.ini 文件中

-Dfile.encoding=UTF-8 

编辑:

我只想添加以下内容。我执行了以下步骤作为实验。

  1. 我打开记事本++并创建了一个新文件
  2. I modified the encoding setting to UTF-8
  3. I copied your Russian text and pasted it in my new text file and saved it.
  4. Next I opened my windows console ("cmd")
  5. I executed the "chcp 65001" command.
  6. Next I printed the content of the file in my console: "type file.txt"
  7. Everything shows correctly.

This does not confirm much, but it does confirm the fact that DOS can do the job if the content is foreseen in the right encoding.

EDIT2:

@ka3ak It's been over 2 years, but while reading a book about Java I/O I stumbled upon the following.

System.console().printf(...) has better support for special characters than the System.out.println(...) method.

Since the PrintStream just wraps around the System.out stream, I guess you have the same limitations. I am wondering if this could have solved the problem. If it still matters, please give it a try. :)

Other posts on stackoverflow report similar things: console.writeline and System.out.println

于 2012-12-06T21:38:32.800 回答
0

After reading the answers and recommendations here I concluded that there must be a problem with JRE. Maybe this problem only exists in Windows 7 (unfortunately I don't have other Windows systems to experiment with).

The solution is to use JNI or if you want a simpler solution then use JNA. I've found a useful JNA example, which solves my problem, here https://stackoverflow.com/a/8921509/971355

于 2012-12-07T06:18:32.773 回答
0

This is due to the a in ¼-hearted implementation of cp65001 in Windows. See the complete disclosure in @eryksun’s answer.

简短的总结:只有 7 位(原文如此!)输入/输出在 cp65001 中可靠地工作(除非 CRTL 做出变通办法)直到 Windows 7。输出问题在 Windows 8 中得到修复。输入问题出现在 Windows 10 中。

于 2017-12-17T08:38:09.673 回答