views:

29

answers:

1

I have the following class in Java which prints "Hello World" in portuguese:

public class PrintUnicode {
    public static void main(String[] args) {
        System.out.println("Olá Mundo!");
    }
}

I am using Eclipse, so I exported the project to a Runnable Jar File. After that, I went to cmd (Windows 7) and ran the generated jar file.

The result was:

Olß Mundo!

Is there an easy way to avoid this error?

+2  A: 

Found the solution. Just change to:

public class PrintUnicode {
    public static void main(String[] args) {
        System.console().printf("Olá Mundo!");
    }
}

The error with System.out happens because:

By default, Java encodes Strings sent to System.out in the default code page. On Windows XP, this means a lossy conversion to an "ANSI" code page. This is unfortunate, because the Windows Command Prompt (cmd.exe) can read and write Unicode characters. (source here)

fjsj
I've workarounded this problem before by encoding manually: `System.out.write(myStr.getBytes(consoleCharset));` but this is far better.
helios