Reputation: 338346
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.
Upvotes: 1
Views: 1142
Reputation:
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.
Upvotes: 0