Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java change the codepage of its own console?

Echoing the conclusions of https://stackoverflow.com/a/17177904/14731, applications need to invoke WriteConsoleW or chcp in order to output unicode characters to the Windows console.

I don't want to use JNI so the WriteConsoleW approach is out. Is it possible for a Java application to invoke chcp on the console it is running inside of?

As far as I know, invoking Runtime.exec("cmd.exe", "/c", "chcp", "65001") will create a new console, change its code-page, and then kill the console. Meaning, the existing console won't be affected.

like image 975
Gili Avatar asked Jan 05 '23 11:01

Gili


1 Answers

Based on a hunch, I tried:

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "chcp", "65001").inheritIO();
Process p = pb.start();
p.waitFor();

and it worked!

inheritIO() causes the child process to inherit the parent's stdout. When chcp modifies the character encoding of the child stdout it actually ends up modifying the parent's encoding as well. Great success! :)

like image 133
Gili Avatar answered Jan 09 '23 09:01

Gili