Java Console Output with UTF-8

20 Jun 2018

Update - for newer versions of Java (17 onwards), things are a bit different. See The NetBeans Output Window - Revisited for details.

Remember:

Java
1
2
3
4
5
import java.io.PrintStream;  
import static java.nio.charset.StandardCharsets.UTF_8;  

PrintStream out = new PrintStream(System.out, true, UTF_8); // true = autoflush  
out.println("读写汉字");

Also, using StandardCharsets.UTF_8 rather than the literal string “UTF-8” avoids the need to handle an UnsupportedEncodingException.

In some cases, you may also need this Java command line option:

-Dfile.encoding=UTF-8

If it’s the console used by NetBeans, add the option to the default options in:

.../netbeans/etc/netbeans.conf  

Something like this (with the additional -J in this case):

netbeans_default_options="... -J-Dfile.encoding=UTF-8"  

An alternative approach in NetBeans is to go to Project Properties > Run > VM Options, and add this:

-Dfile.encoding=UTF-8

After that, the System.out.println("读写汉字") command should work without needing the PrintStream code.

To check what default encoding the JVM is using, use:

Java
1
System.out.println(System.getProperty("file.encoding"));

One final item: If you are using Windows and you want to change the command console to use UTF-8 for output, then run this command:

CHCP 65001  

And make sure you are using a font which can actually display the characters you need to show.