wx_xw 发表于 2013-2-3 10:29:11

java中unicode码转中文

        最近做项目,要把unicode转为中文,但是本身取出来的时候unicode码已经被转为“\\u6211”了,无法用java默认的转码来转换了。
        自己写了一个转换器,根据unicode转码的规律,之后遇到了不少麻烦,例如如果以“\\u”开头但是根本不是unicode码、末尾以“\\”结尾啊什么的。目前是把程序完成为能想到的出错的可能性都覆盖了,以后再碰到再修改。
public class UnicodeDecoder {public static void main(String[] args) {String s = "\\\u6211\\uadsf\\t\\u7231\u5317\\u4EAC\u5929\\u5B\t89\\\t\u95E8\\\"\\u12";System.out.println(decode(s));}public static String decode(String in) {try {return decode(in.toCharArray());} catch (Exception e) {e.printStackTrace();}return in;}private static String decode(char[] in) throws Exception {int off = 0;char c;char[] out = new char;int outLen = 0;while (off < in.length) {c = in;if (c == '\\') {if (in.length > off) { // 是否有下一个字符c = in; // 取出下一个字符} else {out = '\\'; // 末字符为'\',返回break;}if (c == 'u') { // 如果是"\\u"int value = 0;if (in.length > off + 4) { // 判断"\\u"后边是否有四个字符boolean isUnicode = true;for (int i = 0; i < 4; i++) { // 遍历四个字符c = in;switch (c) {case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9':value = (value << 4) + c - '0';break;case 'a':case 'b':case 'c':case 'd':case 'e':case 'f':value = (value << 4) + 10 + c - 'a';break;case 'A':case 'B':case 'C':case 'D':case 'E':case 'F':value = (value << 4) + 10 + c - 'A';break;default:isUnicode = false; // 判断是否为unicode码}}if (isUnicode) { // 是unicode码转换为字符out = (char) value;} else { // 不是unicode码把"\\uXXXX"填入返回值off = off - 4;out = '\\';out = 'u';out = in;}} else { // 不够四个字符则把"\\u"放入返回结果并继续out = '\\';out = 'u';continue;}} else {switch (c) { // 判断"\\"后边是否接特殊字符,回车,tab一类的case 't':c = '\t';out = c;break;case 'r':c = '\r';out = c;break;case 'n':c = '\n';out = c;break;case 'f':c = '\f';out = c;break;default:out = '\\';out = c;break;}}} else {out = (char) c;}}return new String(out, 0, outLen);}}  
 
页: [1]
查看完整版本: java中unicode码转中文