Java IO之编码介绍

原文链接:https://www.codeliu.com/java/259.html

在Java中如何进行文件的读写十分重要,Java IO流是必备的知识点。本文先不讲Java读写的API,先讲一讲关于编码的那些事。

废话不多说,代码是最好的表达方式

public class EncodeDemo { 
    public static void main(String[] args) throws Exception{ 
        String s = "我爱Code";
        // 使用项目默认的编码gbk
        byte[] bytes1 = s.getBytes(); 
        System.out.print("项目默认编码:"); 
        for(byte b:bytes1) { 
            // 把字节转换成int类型,以16进制显示,&0xff是为了把前面的24个0去掉               
            System.out.print(Integer.toHexString(b & 0xff) + "   "); 
        } 
        System.out.println();

        // 使用gbk编码 
        byte[] bytes2 = s.getBytes("gbk"); 
        System.out.print("gbk:"); 
        for(byte b:bytes2) { 
            // 在gbk编码下,一个中文占两个字节,英文占一个字节 
            System.out.print(Integer.toHexString(b & 0xff) + "   "); 
        } 
        System.out.println();

        // 使用utf-8编码
        byte[] bytes3 = s.getBytes("utf-8"); 
        System.out.print("utf-8:"); 
        for(byte b:bytes3) { 
            // 在utf-8编码下,中文占三个字节,英文占一个字节 
            System.out.print(Integer.toHexString(b & 0xff) + "   "); 
        } 
        System.out.println();

        // java是双字节编码utf-16be 
        byte[] bytes4 = s.getBytes("utf-16be"); 
        System.out.print("utf-16be:"); 
        for(byte b:bytes4) { 
            // 在utf-16be编码下,中文占两个字节,英文占两个字节 
            System.out.print(Integer.toHexString(b & 0xff) + "   "); 
        } 
        System.out.println();

        /** 
         * 把字节序列变成字符串时,应保持和原来的编码格式相同,否则是乱码
         */ 
        String ss = new String(bytes4);  //使用项目默认的编码 
        System.out.println(ss); 
        String sss = new String(bytes4, "utf-16be"); //使用utf-16be编码 
        System.out.println(sss); 
    }
}

输出
项目默认编码:ce d2 b0 ae 43 6f 64 65
gbk:ce d2 b0 ae 43 6f 64 65
utf-8:e6 88 91 e7 88 b1 43 6f 64 65
utf-16be:62 11 72 31 0 43 0 6f 0 64 0 65
br1
我爱Code

从结果可以看出,
在项目默认编码下(eclipse中默认编码是gbk),中文占两个字节,英文占一个字节;gbk编码下,中文占两个字节,英文占一个字节;utf-8编码下,中文占三个字节,英文一个字节;utf-16be编码下,中文英文均占两个字节。

同时要注意的是,把字节序列转换成字符串时,编码应保持相同,不然会出现乱码。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值