码迷,mamicode.com
首页 > 编程语言 > 详细

java基础-io

时间:2020-04-13 10:32:52      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:tst   字节   java   div   编码   main   默认   stack   utf-16   

1.编码

public class EncodeDemo {
    public static void main(String[] args) {
        String s = "聪123";
        byte[] b1 = s.getBytes();    //转换成字节序列用的是项目默认的编码
        for (byte b : b1) {
            //把字节转换成以16进制的方式显示
            System.out.print(Integer.toHexString(b & 0xFF) + " ");
        }
        System.out.println();
        try {
            //gbk编码中文占用2个字节,英文占用1个字节
            byte[] b2 = s.getBytes("gbk");
            for (byte b : b2) {
                System.out.print(Integer.toHexString(b & 0xff) + " ");
            }
            System.out.println();

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

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

            /**
             * 当你的字节序列是某种编码时,这个时候想要把字节序列变成字符串,也需要这种编码方式,否则会出现乱码
             */
            String s1 = new String(b4);
            System.out.println(s1);
            String s2 = new String(b4, "utf-16be");
            System.out.println(s2);
            /**
             * 文本文件就是字节序列,可以是任意的字节序列,如果我们在中文机器上创建文本文件,那么这个机器只认识ansi编码
             * 联通,联这是一种巧合,他们正好符合了utf-8编码规则
             */
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

  

2.待续

java基础-io

标签:tst   字节   java   div   编码   main   默认   stack   utf-16   

原文地址:https://www.cnblogs.com/freeht/p/12689660.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!