System.out and UTF8

Remember the post Why I (rarely) Hate Java? Well, this is another of those moments. I was trying to output a string encoded in UTF8 and it was displaying as ??? So, how am I supposed to fix this?

Well, I think, when Java started off, the designers perhaps didn’t bother about encoding. That’s why you see Streams initially in the java.io package and then the readers and writers. The later are aware of encoding while the former classes are not. And unfortunately, the System.in and system.out happen to be the stream classes. As a result, it’s not possible to do utf8 or other non-default encodings.

So, the way to fix this is

PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
out.println(“some-utf8-string”);

Now, this should work just fine. And BTW, if you are trying to see the output in a linux console or using vi editor, you would still see the data as some garbage. One option is to open it in Firefox and make sure that the character encoding is in utf8.

Advertisements

6 Comments

Filed under Java

6 responses to “System.out and UTF8

  1. Pingback: Java String Passwords « poeticcode

  2. oma

    Humm… I have an error.
    There is no constructor for PrintStream that takes an OutputStreamWriter as a parameter.

  3. S

    Oops, the above should have been

    PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    out.println(“some-utf8-string”);

  4. Antigoni

    What about System.in to read utf-8 ?

  5. Attila123

    I had to add
    -Dfile.encoding=UTF-8
    to eclipse.ini to make it work in Eclipse Console, see:
    http://paranoid-engineering.blogspot.de/2008/05/getting-unicode-output-in-eclipse.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s