在 Java 中获取 PrintStream 的字符集

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

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

有没有办法获取Charset对象(例如System.out)使用的printstream?像这样:

Charset charset = System.out.getcharset() ;

...但我在 printstream 上找不到任何这样的 getter。

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

aniu8258 回答:在 Java 中获取 PrintStream 的字符集

你应该像这样使用反射 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

您需要注意最后一条警告信息。

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

enter image description here

本文链接:https://www.f2er.com/697875.html

大家都在问