java unicode 转为汉字

本文介绍如何在Java中实现Unicode与汉字之间的相互转换,包括使用Java内置库完成转换的具体示例代码,同时提供了利用json库进行转换的方法。

原文出处:http://blog.chenlb.com/2009/07/java-unicode-to-chinese.html

网上搜索了一大堆内容,大都是汉字转 unicode 的。要么就理想化的 unicode 转为汉字(全是 \uxxxx 的,用 spilt 取再转的)。记录以前写输出格式为 json 的时候,用过的库是可以把汉定转为 unicode 的,并且也读取。那就用 json 库来转汉字,其实可以自己写个小程序来转,算了懒一下。

我下载官方的 java 的 json的 jar 包。http://www.json.org/java/json.zip, 可以到 http://www.json.org/java/index.html 看 javadoc。

示例代码:

  1. public void testUDecode() {  
  2.     String str = "make in \u4e2d\u56fd";  
  3.     for(char ch : "make in 中国".toCharArray()) {  
  4.         if(ch > 128) {  
  5.             System.out.print("\\u"+Integer.toHexString(ch));  
  6.         } else {  
  7.             System.out.print(ch);  
  8.         }  
  9.     }  
  10.     System.out.println();  
  11.     System.out.println(str);  
  12.     str = "make in \\u4e2d\\u56fd";  
  13.   
  14.     String v = "'"+str+"'";  
  15.     System.out.println(v);  
  16.   
  17.     try {  
  18.         System.out.println(new JSONTokener(v).nextValue().toString());  
  19.     } catch (JSONException e) {  
  20.         e.printStackTrace();  
  21.     }  
  22. }  

本身java 是支持unicode 编码的,所以像 str = "make in \u4e2d\u56fd"; 打印出来是正常的。我们要的转换是对 str = "make in \\u4e2d\\u56fd";。

汉字转 unicode 可以用 Integer.toHexString(ch)。unicode 转汉字关键的是 (char)Integer.parseInt("4e2d", 16)。知了这些就可以自己写程序了。

当然还有 java 的 native2ascii 工具,附上用法:JDK自带的native2ascii工具完全揭密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值