A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

public static void main(String[] args) throws Exception
{
        String str = "田";
        byte[] buf = str.getBytes("UTF-8");  //编码
        System.out.println(Arrays.toString(buf));
        String s1 = new String(buf, "GBK");    //解码错误
        System.out.println(s1);

        byte[] b1 = s1.getBytes("GBK");    //对错误的解码结果进行编码
        System.out.println(Arrays.toString(b1));
        String s2 = new String(b1, "UTF-8");     //再重新按照正确的解码规则进行解码
        System.out.println(s2);
}
为什么我最后显示的不是'田',而是乱码

2 个回复

倒序浏览
菜鸟看不懂,帮顶一个
回复 使用道具 举报
简单来说,比如有0111 1010        1111 0101这两个字节在UTF-8里面有其代表的字符,但是在GBK里面,GBK他不认识这两个,GBK就用同一个字节如 1111 1111来表示不认识的字符并存储,GBK出现了乱码,然后当你用utf-8再来解析的时候,出现的自然也是乱码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马