将中文转换成Unicode码

本文介绍了一个使用Java实现的工具类,该工具可以将中文文本转换为对应的Unicode编码。通过执行一个外部命令调用JDK自带的native2ascii工具完成转换,并展示了具体的代码实现及测试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java做的一个将中文转换成Unicode码的工具类分类:java技术
1.工具代码如下:
package ben;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class Native2Ascii {
static String java_bin_path = "D:\\jdk1.4.2_03\\bin";
// 存放中文的文本文件
static String source_file = "C:\\a.txt";

public static void main(String[] args) {
String result = getUnicodeString(source_file);
System.out.println(result);
}

private static String getUnicodeString(String destFileName) {
StringBuffer tempSb = new StringBuffer();
try {
Process p = Runtime.getRuntime().exec(java_bin_path+ "\\native2ascii.exe " + destFileName);
InputStreamReader child_in = new InputStreamReader(p.getInputStream());
int c;
while ((c = child_in.read()) != -1) {
tempSb.append((char)c);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

return tempSb.toString();
}
}

其中,两个变量需要修改一下。
a1.“java_bin_path”:jdk的bin目录;
a2.“source_file”:要转换的中文所在的文本文件。
2.a.txt文本文件
中文测试
中文

3.输出结果
\u4e2d\u6587\u6d4b\u8bd5
\u4e2d\u6587

 


原文链接: http://www.dlog.cn/nicholascoder/diary/6576

转载于:https://my.oschina.net/moroseyu/blog/51482

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值