日期:2014-05-20  浏览次数:20737 次

紧急求助:如何把文本里保存的utf8编码中文读出来转成汉字
文本里保存的是utf8的原码,怎么样读出来,转换成可读的汉字?

比如,文本内容:中文编码
还原成:中文编码

谢谢!!

------解决方案--------------------
楼主这是unicode 编码。不是utf-8.
------解决方案--------------------
写了一个,楼主参考:
Java code

public class StringToUnicode
{
    public static void main(String[] args) throws Exception
    {
        String str="中文编码";
        str=str.replace("&#x","");                    //去掉多余的字符。"&#x"
        str=str.replace(";","");                    //去掉";"

        String UnicodeString=null;
        UnicodeString=stringToUnicode(str);
        System.out.println(UnicodeString);
    }

    //把字符串转换成Unicode字符串,输入的字符串中只能是0-9数字或者是A--F字母,不能有任何其他字符
    //输入字符串要是偶数个字符。
    public static String stringToUnicode(String str) throws Exception
    {
        byte[] bytes=new byte[str.length()/2+2];    //定义字节数组,长度为字符串的一半。加 2 是存放unicode 编码头(ff,fe)
        bytes[0]=-2;                    //-2  对应fe,-1对应ff. 后面要交换,所以保存 fe,ff.
        bytes[1]=-1;
        byte tempByte=0;                //临时变量。
        byte tempHigh=0;
        byte tempLow=0;
        for(int i=0,j=2;i<str.length();i+=2,j++)        //每循环处理2个字符,最后形成一个字节。
        {
            tempByte=(byte)(((int)str.charAt(i))&0xff);    //处理高位。
            if(tempByte>=48&&tempByte<=57)
            {
                tempHigh=(byte)((tempByte-48)<<4);    //'0'对应48。
            }
            else if(tempByte>=65&&tempByte<=70)        //'A'--'F' 
            {
                tempHigh=(byte)((tempByte-65+10)<<4);
            }

            tempByte=(byte)(((int)str.charAt(i+1))&0xff);    //处理低位。
            if(tempByte>=48&&tempByte<=57)
            {
                tempLow=(byte)(tempByte-48);
            }
            else if(tempByte>=65&&tempByte<=70)        //'A'--'F'
            {
                tempLow=(byte)(tempByte-65+10);        //'A'对应10.(或0xa.)
            }
            bytes[j]=(byte)(tempHigh|tempLow);        //通过‘或’加在一起。
        }
        
        for(int i=0;i<bytes.length;i+=2)
        {
            byte b1=bytes[i];
            bytes[i]=bytes[i+1];
            bytes[i+1]=b1;
        }
        String result=new String(bytes,"Unicode");
        return result;
    }
}