IO流之转换流

2020-08-23  本文已影响0人  程序员小杰

上一篇:IO流之缓冲流 https://www.jianshu.com/p/f80daa6fe45f

在IDEA中,使用FileReader读取项目中的文本文件。由于IDEA的设置,都是默认的 UTF-8编码,所以没有任何问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。

 public static void main(String[] args) throws Exception {
        FileReader fr = new FileReader("IO流\\GBK.txt");
        char[] c = new char[6];
        int len = 0;
        while ( (len = fr.read(c) ) != -1){
            System.out.println(new String(c));
        }
    }

结果:
������
������
������

那么如何读取GBK编码的文件呢?

1、OutputStreamWriter

java.io.OutputStreamWriter,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。(编码:把能看懂的变成看不懂)
继承自父类的成员方法:

1.1 构造方法(常用)

1.2 参数

OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("a.txt")); 
OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("a.txt") , "GBK");

1.3 指定编码写出

 public static void main(String[] args) throws Exception {
       //创建FileOutputStream对象,构造方法传递写入数据目的地
        FileOutputStream os = new FileOutputStream("IO流\\GBK.txt");
      //创建OutputStreamWriter对象,构造方法中传递字节输出流和指定的编码表名称
        OutputStreamWriter osw = new OutputStreamWriter(os,"GBK");
//使用OutputStreamWriter中的方法write,把字符转换为字节保存到缓冲区中
        osw.write("我好棒棒哦");
//使用OutputStreamWriter中的方法flush,将缓冲区的字节刷新到文件中
        osw.flush();
//释放资源
        osw.close();
    }

使用IDEA软件打开文件


image.png

2、InputStreamReader

InputStreamReader ,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。(解码:把看不懂的变成能看懂的)
继承自父类的成员方法:

2.1 构造方法(常用)

2.2 参数

2.3 指定编码读取

 public static void main(String[] args) throws Exception {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("IO流\\GBK.txt"));

        int len = 0;
        char[] c = new char[1024];
        while ((len = isr.read(c)) != -1){
            System.out.println(new String(c));
        }
    }

结果:
�Һð���Ŷ

乱码。这是因为UTF-8的编码是不能读取GBK编码文件的。

public static void main(String[] args) throws Exception {
        InputStreamReader isr = new InputStreamReader(new FileInputStream("IO流\\GBK.txt"),"GBK");

        int len = 0;
        char[] c = new char[1024];
        while ((len = isr.read(c)) != -1){
            System.out.println(new String(c,0,len));
        }
    }
结果:
我好棒棒哦
上一篇 下一篇

猜你喜欢

热点阅读