java更改控制台,Java可以更改自己的控制台的代码页吗?

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.

解决方案

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! :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值