我们知道可以用\u8425这样一个转义字符来代表一个字符
同样,如果定义String string = new String("\u8425\u5be8");
这样,string会代表2个中文字的字符。但是我现在遇到一个问题,我的一个字符串是从inputstream读来的,字符串里保存的值就是\u8425\u5be8
如果输出这个字符串,也是输出的\u8425\u5be8,我想大概java在内部把它存为了\\u8425\\u5be8,请问我该如何把这个转义过的字符串重新编码成中文呢?有没有比较现成的JAVA类库?

解决方案 »

  1.   


    import java.io.*;
    public class UnicodeTest{
        public static String parseUnicode(String line){
         int len=line.length();
         char[] out=new char[len];//保存解析以后的结果
         int outLen=0;
         for(int i=0;i<len;i++){
          char aChar=line.charAt(i); 
          if(aChar=='\\'){
           aChar=line.charAt(++i);
           if(aChar=='u'){
            int value=0;
            for(int j=0;j<4;j++){
             aChar=line.charAt(++i);
             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';
             break;
             case 'a': case 'b': case 'c':
             case 'd': case 'e': case 'f':
             value = (value << 4) + 10 + aChar - 'a';
             break;
             case 'A': case 'B': case 'C':
             case 'D': case 'E': case 'F':
             value = (value << 4) + 10 + aChar - 'A';
             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++] = aChar;
       }
      }
      return new String (out, 0, outLen);
     }
      public static void main(String rags[])throws Exception{
         BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("1.txt")));
         String line="";
         while((line=br.readLine())!=null){
            System.out.println(parseUnicode(line));
         }
         br.close();
      }
    }
    输出结果:营寨
    1.txt:
    \u8425\u5be8
      

  2.   

    goldenfish1919把string类型数据演绎的淋漓精致啊,顶
      

  3.   

    楼主对于\u似乎有点误解,在java中\u后跟四位16进制数代表了unicode编码,支持几乎所有国家的语言,说点题外话,\u即使在注释中也不能随便写,编译器也会解析,如果后四位16进制数格式不正确可能无法通过编译。顶一下2楼,真是相当优秀啊~
      

  4.   

    写那么多,为什么不用if(...>..&&...<...)判断呢,应该比switch好吧?