【发布时间】:2023-03-31 23:57:02
【问题描述】:
Java 如何确定System.out 使用的编码?
给定以下类:
import java.io.File;
import java.io.PrintWriter;
public class Foo
{
public static void main(String[] args) throws Exception
{
String s = "xxäñxx";
System.out.println(s);
PrintWriter out = new PrintWriter(new File("test.txt"), "UTF-8");
out.println(s);
out.close();
}
}
它保存为 UTF-8,并在 Windows 系统上使用javac -encoding UTF-8 Foo.java 编译。
之后在 git-bash 控制台上(使用 UTF-8 字符集)我会这样做:
$ java Foo
xxõ±xx
$ java -Dfile.encoding=UTF-8 Foo
xxäñxx
$ cat test.txt
xxäñxx
$ java Foo | cat
xxäñxx
$ java -Dfile.encoding=UTF-8 Foo | cat
xxäñxx
这里发生了什么?
显然 java 会检查它是否连接到终端并在这种情况下更改其编码。有没有办法强制 Java 简单地输出纯 UTF-8?
我也在 cmd 控制台上进行了同样的尝试。重定向 STDOUT 似乎在那里没有任何区别。如果没有 file.encoding 参数,它会输出 ansi 编码,而它会输出 utf8 编码。
【问题讨论】:
-
System.out使用default encoding 对字节进行编码。有时这甚至是控制台使用的编码。 -
但是为什么
java Foo输出的东西与java Foo|cat不同呢? - 默认编码应该是一样的。 -
您确定您确实保存了使用 utf-8 编码的文件吗?依赖源文件编码通常是个坏主意。为了真正安全,请使用
"\u"转义定义字符串。
标签: java windows utf-8 character-encoding console