三、关于java中的IO的基础知识点之字符编码

一、背景

1.我们常用的字符集,其实就是来选择合适的码表就能完成字符和二进制数据之间的转换,从而实现数据的传输。

2.常见的字符码表有,ASCII、ISO8859-1、GB2312、GBK、GB18030、Unicode、UTF-8等。

3.在java编程中,经常会出现字符转换为字节或者字节转换为字符的操作,一般来说把字符串转化为计算机识别的字节序列称为编码,而把字节序列转化为普通人能看懂的明文。

二、代码例子

1.代码编写

 public static void main(String[] args) throws Exception {
        String str = "学生";
        byte[] b1 = str.getBytes();//使用默认的码表编码
        byte[] b2 = str.getBytes("GBK");//使用GBK编码
        byte[] b3 = str.getBytes("UTF-8");//打印出字节数组的字符串形式
        //使用String类的构造方法String(byte[] byte,String charsetName) ISO8859-1
        String result1 = new String(b1, "UTF-8");
        System.out.println(result1);

        String result2 = new String(b2, "GBK");
        System.out.println(result2);

        String result3 = new String(b3, "UTF-8");
        System.out.println(result3);
    }

2.结果

学生
学生
学生

3.结果分析

1.同样的编码用同样的解码,那如果是不同的可以解密吗?可以的,接下来我们就来试试。

三、代码示例

1.代码

public static void main(String[] args) throws Exception {
        String str = "学生";
        byte[] b = str.getBytes("GBK");//使用GBK编码
        String temp = new String(b, "ISO8859-1");
        System.out.println(temp);//用错误的码表解码,打印出了乱码
        byte[] b1 = temp.getBytes("ISO8859-1");//在使用错误的码表编码
        String result = new String(b1, "GBK");//用正确的码表解码
        System.out.println(result);//打印正确的结果
    }

2.结果

这样是可以打印出正确的结果的,但是这样并不是每次都能得到正确的结果的,还是按照第一种方式是比较保险的。

四、关于字符传输

1.如果通过FileReader和FileWriter读取一个编码格式为GBK的文件,并将读取到的数据写入一个编码格式为UTF-8的文件中时,则一定会出现乱码现象。

2.代码

public static void main(String[] args) throws Exception{
        //创建InputStreamReader对象
        Reader reader = new InputStreamReader(new FileInputStream("E://1.txt"), "GBK");
        //创建OutputStreamWriter对象
        Writer writer = new OutputStreamWriter(new FileOutputStream("E://2.txt"), "UTF-8");
        //定义一个字符数组
        char[] chs = new char[100];
        int len;
        len = reader.read(chs);
        String string = new String(chs, 0, len);
        writer.write(string);
        reader.close();
        writer.close();
    }

3.分析

上面这样操作完之后就能正确的将字节转化为字符,从而避免了程序在读写操作时的乱码问题啦!!

五、结束

1.今天就学习到这里吧!!!

发布了122 篇原创文章 · 获赞 64 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/chenmingxu438521/article/details/102463611
今日推荐