Java:如何检测(和更改?)System.console 的编码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2415597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to detect (and change?) encoding of System.console?
提问by Epaga
I have a program which runs on a console and its Umlauts and other special characters are being output as ?'s on Macs. Here's a simple test program:
我有一个在控制台上运行的程序,它的元音变音和其他特殊字符在 Mac 上以 ? 的形式输出。这是一个简单的测试程序:
public static void main( String[] args ) {
System.out.println("h?h??ü?");
System.console().printf( "h?h??ü?" );
}
On a default Mac console (with default UTF-8 encoding), this prints:
在默认的 Mac 控制台上(使用默认的 UTF-8 编码),它会打印:
h?h????
h?h????
But after manually setting the Mac terminal's encoding to "Mac OS Roman", it correctly printed
但是在手动将 Mac 终端的编码设置为“Mac OS Roman”后,它正确打印
h?h??ü?
h?h??ü?
Note that on Windows systems using System.console() works:
请注意,在 Windows 系统上使用 System.console() 工作:
h÷h÷?3?
h?h??ü?
So how do I make my program...rolleyes..."run everywhere"?
那么我如何让我的程序... rolleyes...“到处运行”?
采纳答案by gamma
Epaga: have a look right here. You can set the output encoding in a printstream - just have to determine or be absolutely sure about which is being set.
Epaga:看看这里。您可以在打印流中设置输出编码 - 只需确定或绝对确定正在设置的编码。
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Test {
public static void main (String[] argv) throws UnsupportedEncodingException {
String unicodeMessage =
"\u7686\u3055\u3093\u3001\u3053\u3093\u306b\u3061\u306f";
PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(unicodeMessage);
}
}
To determine the console encoding you could use the system command "locale" and parse the output which - on a german UTF-8 system looks like:
要确定控制台编码,您可以使用系统命令“locale”并解析输出 - 在德国 UTF-8 系统上如下所示:
LANG="de_DE.UTF-8"
LC_COLLATE="de_DE.UTF-8"
LC_CTYPE="de_DE.UTF-8"
LC_MESSAGES="de_DE.UTF-8"
LC_MONETARY="de_DE.UTF-8"
LC_NUMERIC="de_DE.UTF-8"
LC_TIME="de_DE.UTF-8"
LC_ALL=
回答by Bozho
Try the following command-line argument when starting your application:
在启动应用程序时尝试以下命令行参数:
-Dfile.encoding=utf-8
-Dfile.encoding=utf-8
This changes the default encoding of the JVM for I/O operations.
这会更改 JVM 用于 I/O 操作的默认编码。
You can also try:
您也可以尝试:
System.setOut(new PrintStream(System.out, true, "utf-8"));