java输出utf8_用java在Windows控制台输出utf8字符

最近开发java控制台项目,由于用了第三方库,必须使用utf8字符。当然在开发环境eclipse下,显示是正常的:

4e8bdf3cf55ae7e6fa35a5dcaf165156.png

但是windows的控制台,却是输出乱码。

5b0d8b5bf34df7691e68e1aeb74eab8e.png

虽然不改,程序逻辑是正确,作为偏执狂还是翻阅了各种资料:

网上各种文章,不是用chcp改变控制台编码,就是建议修改程序编码为GBK。

参考了stackoverflow的一篇文章,找到一种使用Windows内核API的方案

核心是封装一个Console类 package demo;

import com.sun.jna.Native;

import com.sun.jna.Pointer;

import com.sun.jna.ptr.IntByReference;

import com.sun.jna.win32.StdCallLibrary;

/**

* For unicode output on windows platform

*

* @author Sandy_Yin

*

*/

public class Console {

private static Kernel32 INSTANCE = null;

public interface Kernel32 extends StdCallLibrary {

public Pointer GetStdHandle(int nStdHandle);

public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer,

int nNumberOfCharsToWrite,

IntByReference lpNumberOfCharsWritten, Pointer lpReserved);

}

static {

String os = System.getProperty("os.name").toLowerCase();

if (os.startsWith("win")) {

INSTANCE = (Kernel32) Native

.loadLibrary("kernel32", Kernel32.class);

}

}

public static void print(String message) {

if (!prePrint(message))

System.out.print(message);

}

protected static boolean prePrint(String message) {

boolean successful = false;

if (INSTANCE != null) {

Pointer handle = INSTANCE.GetStdHandle(-11);

char[] buffer = message.toCharArray();

IntByReference lpNumberOfCharsWritten = new IntByReference();

successful = INSTANCE.WriteConsoleW(handle, buffer, buffer.length,

lpNumberOfCharsWritten, null);

}

return successful;

}

public static void println(String message) {

// from

// http://stackoverflow.com/questions/54952/java-utf-8-and-windows-console

if (prePrint(message)) {

System.out.println();

} else {

System.out.println(message);

}

}

}

对输出进行测试,使用命令:java -jar sample.jar,发现输出还是一样。

dfd3d630c5ee24ba46cc4b3dffab6f7c.png添加命令行参数,使用java -Dfile.encoding=utf8 -jar sample.jar,就达到效果了。

e53adbcb02e3f5fa9f9ecdf16cdeb2ca.png

PS:此方法还存在一些缺陷,但并不是Console类造成的。上图中“测试”前有一个空白的地方,这是应为使用utf8方式读入非UTF8文件产生的。在文件开始会出现空格。

代码下载/Files/anic/utf8sample_source.zip

/Files/anic/utf8sample_runtime.zip

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值