0

我知道我们可以这样设置CharsetPrintStream

PrintStream printStream = new PrintStream( System.out, true, StandardCharsets.UTF_8.name() );  // "UTF-8".

有没有办法对象使用CharsetPrintStream例如System.out?像这样的东西:

Charset charset = System.out.getCharset() ;

……但我在 . 上找不到任何这样的吸气剂PrintStream

这个问题是在解决这个问题中的一个谜时提出的。

4

1 回答 1

0

您应该像这样使用反射 API。

PrintStream ps = new PrintStream(System.out, true, StandardCharsets.UTF_16);
Field f = ps.getClass().getDeclaredField("charOut");
f.setAccessible(true);
OutputStreamWriter charOut = (OutputStreamWriter) f.get(ps);
System.out.println(charOut.getEncoding());

输出:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by stackoverflow.AAA field java.io.PrintStream.charOut
WARNING: Please consider reporting this to the maintainers of stackoverflow.AAA
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

UTF-16

您需要注意最后一条 WARNING 消息。

charOut我在我的 Eclipse 调试器中找到了该字段。

在此处输入图像描述

于 2021-03-25T02:48:45.620 回答