测试代码
package cn.java.codec.unicode;public class Test { public static void main(String[] args) throws Exception {
String str = "test中文";
String unicodeEncode = UnicodeUtil.encode(str);
System.out.println("UnicodeUtil.encode Result : " + unicodeEncode);
str = UnicodeUtil.decode(unicodeEncode);
System.out.println("UnicodeUtil.decode Result : " + str);
}
}
输出内容
UnicodeUtil.encode Result : \u0074\u0065\u0073\u0074\u4e2d\u6587 UnicodeUtil.decode Result : test中文
工具类
package cn.java.codec.unicode;/**
* 每六位描述一个字节
* @author zhouzhian */public class UnicodeUtil {
/**
* 字符串编码成Unicode编码 */
public static String encode(String src) throws Exception { char c;
StringBuilder str = new StringBuilder(); int intAsc;
String strHex; for (int i = 0; i < src.length(); i++) {
c = src.charAt(i);
intAsc = (int) c;
strHex = Integer.toHexString(intAsc); if (intAsc > 128)
str.append("\\u" + strHex); else
str.append("\\u00" + strHex); // 低位在前面补00 } return str.toString();
}
/**
* Unicode解码成字符串
* @param src
* @return
*/
public static String decode(String src) { int t = src.length() / 6;
StringBuilder str = new StringBuilder(); for (int i = 0; i < t; i++) {
String s = src.substring(i * 6, (i + 1) * 6); // 每6位描述一个字节 // 高位需要补上00再转
String s1 = s.substring(2, 4) + "00"; // 低位直接转
String s2 = s.substring(4); // 将16进制的string转为int
int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16); // 将int转换为字符
char[] chars = Character.toChars(n);
str.append(new String(chars));
} return str.toString();
}
}
