Java可以更改自己的控制台的代码页吗? [英] Can Java change the codepage of its own console?
问题描述
回应 https://stackoverflow.com/a/17177904/14731 的结论,应用程序需要调用 WriteConsoleW
或 chcp
,以便将unicode字符输出到Windows控制台。
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.
我不想使用JNI,因此 WriteConsoleW
方法已经完成。 Java应用程序是否可以在其内部运行的控制台上调用 chcp
?
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?
据我所知,调用 Runtime.exec(cmd.exe,/ c,chcp,65001)将创建一个新的控制台,更改其代码页,以及然后杀掉控制台。意思是,现有的控制台不会受到影响。
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.
推荐答案
基于预感,我试过:
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "chcp", "65001").inheritIO();
Process p = pb.start();
p.waitFor();
它有效!
inheritIO()
导致子进程继承父进程的 stdout
。当 chcp
修改子元素 stdout
的字符编码时,它实际上也会修改父代的编码。巨大的成功! :)
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! :)
这篇关于Java可以更改自己的控制台的代码页吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!