`

Java unicode中文编码转换和反转

阅读更多

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

参考网址:

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;
        }
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics