编码与解码以及乱码问题出现的原因

import java.io.UnsupportedEncodingException;

public class BianMaDemo3 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        /*
         * 编码和解码的概念
         * 编码 : 字符 ->编码字符集 ->二进制;
         * 解码 : 二进制 ->解码字符集 -> 字符;
         * 
         * 乱码问题出现的原因:
         * 编码与解码的字符集不统一
         * 字节缺少,长度丢失
         */
        
        
        
        /*
         * 编码与解码的字符集不统一
         */
        String s="你好";
        byte[] bys=s.getBytes("GBK");
        System.out.println(new String(bys));//Java中默认GBK
        bys=s.getBytes("UTF-8");
        System.out.println(new String(bys));//将中文的utf-8编码,作为字符串的GBK编码,所以乱码
        /*
         * 字节缺少,长度丢失
         */
        System.out.println(new String(bys,0,1));
        
        
        
    }

}
运行结果:
中国 涓浗
?

 

posted @ 2020-02-10 22:09  /*nobody*/  阅读(321)  评论(0编辑  收藏  举报