JAVA编码与解码概念,出现乱码的原因

编码:字符----》二进制;

解码:二进制----》字符;

计算机存储的都是二进制。

public static void main(String[] args) throws UnsupportedEncodingException {
        String str = "努力";   
        //编码 char--->byte   默认使用gbk编码
        byte[] data = str.getBytes();
        //解码 byte-->char   默认使用gbk
        str = new String(data);
        System.out.println("---------解码编码方式均为默认,不会乱码----------------");
        System.out.println(str);


        //使用utf-8编码
        data=str.getBytes("utf-8");  
        //不统一出现乱码:使用默认gbk解码
        str = new String(data);  
        System.out.println("---------编码用的utf-8,解码默认gbk,出现乱码----------------");
        System.out.println(str); 
        
        //使用utf-8编码
        byte[] data2 = "努力".getBytes("utf-8");
        //解码 使用utf-8,指定统一的解码方式
        str = new String(data2,"utf-8");
        System.out.println("---------编码用的utf-8,解码也用的utf-8,不会乱码----------------");
        System.out.println(str);
        
        //因字节数不完整出现乱码
        System.out.println("---------因字节数不完整出现乱码----------------");
        System.out.println(new String(data,0,3));
    }

运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值