中文和Unicode互相转化

Unicode转中文

1
2
3
String unicode = "\u6211\u7231\u7956\u56fd";
String result = new String(unicode.getBytes("UTF-8"), "UTF-8");
System.out.println(result);

结果:我爱祖国

中文转Unicode

1
2
3
4
5
6
7
String chinese = "我爱祖国";
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < chinese.length(); i++) {
Character character = chinese.charAt(i);
unicode.append("\\u" + Integer.toHexString(character));
}
System.out.println(unicode.toString());

结果:\u6211\u7231\u7956\u56fd

分享到