How to get console (cmd.exe in windows, linux shell, or eclipse console output) charset encoding?
java.nio.charset.Charset.defaultCharset()
seems to be only for input/output files, not console.
There is no standardized way to get that information from the system. Usually it will be the platform default encoding, but as you've noticed, that's not necessarily the case (it's not documented, as far as I know).
You could go the ugly route and use reflection to find out which encoding Java uses. The following code is entirely un-portable and has only been verified to work on one specific version of the OpenJDK, it's experimentation and not meant for production:
final Class<? extends PrintStream> stdOutClass = System.out.getClass();
final Field charOutField = stdOutClass.getDeclaredField("charOut");
charOutField.setAccessible(true);
OutputStreamWriter o = (OutputStreamWriter) charOutField.get(System.out);
System.out.println(o.getEncoding());
This prints UTF8
[sic] on my system, which isn't surprising, as I'm using a UTF-8 locale on a Linux machine.
Since JDK 1.1, you can construct an OutputStreamWriter using the System out field, and call getEncoding().
OutputStreamWriter osw = new OutputStreamWriter(System.out);
System.out.println(osw.getEncoding());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With