Java:如何检测(和更改?) System.console 的编码?
我有一个在控制台上运行的程序,它的元音变音和其他特殊字符在 Mac 上输出为?这是一个简单的测试程序:
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:
public static void main( String[] args ) {
System.out.println("höhößüä");
System.console().printf( "höhößüä" );
}
在默认的 Mac 控制台(使用默认的 UTF-8 编码)上,会打印:
On a default Mac console (with default UTF-8 encoding), this prints:
h?h????
h?h????
但是手动设置Mac终端的编码为Mac OS Roman"后,打印正确
But after manually setting the Mac terminal's encoding to "Mac OS Roman", it correctly printed
höhößüä
höhößüä
请注意,在 Windows 系统上使用 System.console() 有效:
Note that on Windows systems using System.console() works:
h÷h÷▀³õ
höhößüä
那么我该如何让我的程序...rolleyes...到处运行"?
So how do I make my program...rolleyes..."run everywhere"?
推荐答案
Epaga: 看看吧这里.您可以在打印流中设置输出编码 - 只需确定或绝对确定要设置的编码.
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.
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class Test {
public static void main (String[] argv) throws UnsupportedEncodingException {
String unicodeMessage =
"u7686u3055u3093u3001u3053u3093u306bu3061u306f";
PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(unicodeMessage);
}
}
要确定控制台编码,您可以使用系统命令locale"并解析输出 - 在德国 UTF-8 系统上,如下所示:
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:
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=
相关文章