Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get console charset?

Tags:

java

console

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.

like image 576
tmp Avatar asked May 30 '11 06:05

tmp


2 Answers

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.

like image 145
Joachim Sauer Avatar answered Oct 02 '22 23:10

Joachim Sauer


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());
like image 25
ubzack Avatar answered Oct 02 '22 22:10

ubzack