Java unicode中文编码转换和反转

参考网址http://www.oschina.net/code/snippet_142385_4297

http://canofy.iteye.com/blog/718659

在java的很多配置文件中,尤其是国际化资源中经常遇到类似\uf432这样的unicode编码,搜集了下该编码相关的资料,大致处理方法有如下:

1、Unicode转 汉字字符串。

这个过程最简单的方式就是直接获取。比如

String cnStr = "\ufeff\u4e2d\u56fd\u4eba";

System.out.println(cnStr); 即可获取对应的汉字字符  “中国人”;

但是呢,每次从输出读的话也未免过于不方便了,我们使用方法来做转换,直接获取。

参考如下

	public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");    
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");    
        }
        return str;
    }

2、获取字符串的unicode编码,这个我们可以通过直接获取字符串的unicode二进制,然后将其byte转换成对应的16进制表示即可,函数示例如下

static String getUnicode(String s) {
		try {
			StringBuffer out = new StringBuffer("");
			byte[] bytes = s.getBytes("unicode");
			for (int i = 0; i < bytes.length - 1; i += 2) {
				out.append("\\u");
				String str = Integer.toHexString(bytes[i + 1] & 0xff);
				for (int j = str.length(); j < 2; j++) {
					out.append("0");
				}
				String str1 = Integer.toHexString(bytes[i] & 0xff);
				out.append(str1);
				out.append(str);
				
			}
			return out.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

 

通过上面的方式便可完整的使用unicode编码了,大家有其他方式的转换也可以告诉我下,互相学习

转载于:https://www.cnblogs.com/xignzou/p/3329438.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值