unicode转中文代码

public static String loadConvert(String src) {
        char[] in = new char[src.length()];
        src.getChars(0, src.length()-1, in, 0);
        char[] convtBuf = new char[in.length];
        int len = in.length;
        int off = 0;
        char aChar;
        char[] out = convtBuf; // 保存输出结果
        int outLen = 0;
        int end = off + len;

        while (off < end) {
            aChar = in[off++];
            if (aChar == '\\') {// 将u中的\匹配出来
                aChar = in[off++];
                if (aChar == 'u') {// 将uxxxx中的u匹配出来
                    // Read the xxxx
                    int value = 0;
                    for (int i = 0; i < 4; i++) {
                        aChar = in[off++];
                        switch (aChar) {
                        case '0':
                        case '1':
                        case '2':
                        case '3':
                        case '4':
                        case '5':
                        case '6':
                        case '7':
                        case '8':
                        case '9':
                            value = (value << 4) + aChar - '0'; // 如果是读进字符是0-9,则让0+aChar-'0'(即字符0的ascii值)
                            break;
                        case 'a':
                        case 'b':
                        case 'c':
                        case 'd':
                        case 'e':
                        case 'f':
                            value = (value << 4) + 10 + aChar - 'a';// 如果是读进字符是a-f,则让0+10+aChar-'a'(即字符a的ascii值)
                            break;
                        case 'A':
                        case 'B':
                        case 'C':
                        case 'D':
                        case 'E':
                        case 'F':
                            value = (value << 4) + 10 + aChar - 'A';// 如果是读进字符是A-Z,则让0+aChar-'A'(即字符A的ascii值)
                            break;
                        default:
                            throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
                        }
                    }
                    out[outLen++] = (char) value;
                } else {// 其他制表符原因输出
                    if (aChar == 't')
                        aChar = '\t';
                    else if (aChar == 'r')
                        aChar = '\r';
                    else if (aChar == 'n')
                        aChar = '\n';
                    else if (aChar == 'f')
                        aChar = '\f';
                    out[outLen++] = aChar;
                }
            } else {
                out[outLen++] = (char) aChar;// 将转换的value保存为char类型用于显示
            }
        }
        return new String(out, 0, outLen);
    }

posted @ 2012-09-02 23:51  箫起之曲  阅读(468)  评论(0编辑  收藏  举报