RFC: System.console().encoding()

Xueming Shen xueming.shen at oracle.com
Thu Sep 15 16:40:14 UTC 2016

On 9/15/16 8:56 AM, Aleksey Shipilev wrote:
> On 09/15/2016 09:06 AM, Xueming Shen wrote:
>> Console is supposed to be a "char/String" based class, "encoding"
>> really should have no business here in its api. Simply for some
>> implementation convenience is really not a good reason to add such a
>> public method.
> Let's look at it this way: there is a problem with console encoding that
> Console class solves, nicely abstracting the subtleties away. In doing
> so, it polls GetConsoleCP, the WinAPI call:

What I meant is that the Console was/is designed the way that the user 
can access
the console/terminal without knowing/dealing with the "encoding". The 
concept is purposely hidden from the very beginning, with the 
that this is a implementation detail you really don't need to know when 
using the
Console class in general use scenario. It's obviously it would be 
helpful and convenient
if this encoding info can be accessed in your use case, but given this 
is really not a
"normal" use scenario, what I'm saying is the System properties might be 
better place
for such information. Seems like the jmh.util.Utils is accessing the 
already for other system/vm-wide info, such as the vm version, os.name 
...as well
as the file.encoding you might need for non-console in/output.


> Java_java_io_Console_encoding(JNIEnv *env, jclass cls)
> {
>      char buf[64];
>      int cp = GetConsoleCP();
>      if (cp >= 874 && cp <= 950)
>          sprintf(buf, "ms%d", cp);
>      else
>          sprintf(buf, "cp%d", cp);
>      return JNU_NewStringPlatform(env, buf);
> }
> If by "convenience" you mean avoiding doing the JNI call that polls that
> OS-specific bit of data, then yes, APIs provide lots of those conveniences.
>> That said, I would be fine to have such informative info in the
>> system properties, together with its siblings, file,encoding and
>> another "supposed to be private" property sun.jnu.encoding.
> Actually, if you look into the launcher, it does:
> static char* getConsoleEncoding()
> {
>      char* buf = malloc(16);
>      int cp;
>      if (buf == NULL) {
>          return NULL;
>      }
>      cp = GetConsoleCP();
>      if (cp >= 874 && cp <= 950)
>          sprintf(buf, "ms%d", cp);
>      else
>          sprintf(buf, "cp%d", cp);
>      return buf;
> }
> ...
>    sprops.sun_stdout_encoding = getConsoleEncoding();
> ...which opens a way to poll this without a Reflection hack. Extended
> the JMH hack with it, but it still fragile:
>   http://hg.openjdk.java.net/code-tools/jmh/rev/8c20adb08b2d
> Thanks,
> -Aleksey

More information about the core-libs-dev mailing list