Unicode编码转中文 方法1 需要引入2个包
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Unicode编码转换工具
* */
public class UnicodeToUtil {
// Unicode编码转中文 方法1
// 使用 Pattern 和 Matcher
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;
}
// Unicode编码转中文 方法2
private static String unicodeToCn(String unicode) {
String[] strs = unicode.split("\\u");
String returnStr = "";
for (int i = 1; i < strs.length; i++) {
returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
}
return returnStr;
}
// 中文转Unicode
private static String cnToUnicode(String cn) {
char[] chars = cn.toCharArray();
String returnStr = "";
for (int i = 0; i < chars.length; i++) {
returnStr += "\u" + Integer.toString(chars[i], 16);
}
return returnStr;
}
}
输出结果
Unicode转中文:\u54c8\u54c8 =》哈哈
中文转Unicode:哈哈 =》\u54c8\u54c8