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编码了,大家有其他方式的转换也可以告诉我下,互相学习

posted @ 2013-09-19 00:17  行走_  阅读(30381)  评论(0编辑  收藏  举报