【问题标题】:Get the charset of a PrintStream in Java在 Java 中获取 PrintStream 的字符集
【发布时间】:2021-03-25 00:03:52
【问题描述】:

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

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

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

Charset charset = System.out.getCharset() ;

...但我在PrintStream 上找不到任何此类吸气剂。

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

【问题讨论】:

  • PrintStream 被记录在其中有一个OutputStreamWriter。我猜你最后的办法是找到 OutputStreamWriter 字段,然后在上面调用 getEncoding...
  • 这不是系统属性file.encoding的值吗?

标签: java character-encoding getter printstream charset


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 2014-07-06
    相关资源
    最近更新 更多