1

I know we can set the Charset of a PrintStream like this:

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

Is there a way to get the Charset being used by a PrintStream object such as System.out? Something like this:

Charset charset = System.out.getCharset() ;

…but I cannot find any such getter on PrintStream.

This Question was raised while addressing a mystery in this Question.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    `PrintStream` is documented to have an `OutputStreamWriter` inside it. I guess your last resort is to find that `OutputStreamWriter` field, and call `getEncoding` on it... – Sweeper Mar 25 '21 at 01:02
  • Wouldn't that be the value of system property `file.encoding`? – Andreas Mar 25 '21 at 02:22

1 Answers1

0

You should use reflection API like this.

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());

output:

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

You need to pay attention to the last WARNING message.

I found the field charOut in my eclipse debugger.

enter image description here