Java IO流基础2--缓冲流、转换流、序列化流、重定向流

有关IO流基础(包括IO流分类体系,基础文件输入输出流等),请看上一篇https://www.cnblogs.com/gbxblog/p/14027120.html

缓冲流

概述

  缓冲流,也叫高效流,是对4个基本的File文件流的增强,所以也是4个流,按照数据类型分类:
  • 字节缓冲流: BufferedInputStream , BufferedOutputStream
  • 字符缓冲流: BufferedReader , BufferedWriter

缓冲流的基本原理

  在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。

字节缓冲流

构造方法

  • public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
  • public BufferedOutputStream(OutputStream out) : 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字节缓冲输入流 
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt")); 
// 创建字节缓冲输出流 
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

效率测试

1. 基本流,代码如下:

public class BufferedDemo { 
    public static void main(String[] args) throws FileNotFoundException { 
        // 记录开始时间 
        long start = System.currentTimeMillis(); 
        // 创建流对象 
        try (
              FileInputStream fis = new FileInputStream("jdk9.exe"); 
              FileOutputStream fos = new FileOutputStream("copy.exe") 
        ){
              // 读写数据 
             int b; 
             while ((b = fis.read()) != ‐1) { 
                  fos.write(b); 
             } 
        } catch (IOException e) { 
             e.printStackTrace(); 
        }
        // 记录结束时间 
        long end = System.currentTimeMillis(); 
        System.out.println("普通流复制时间:"+(end ‐ start)+" 毫秒"); 
    } 
}    
这种是最基本的文件输入输出流,当然也是速度最慢的。
举例用的是jdk9(375MB),需要10多分钟。

2. 缓冲流,代码如下:

public class BufferedDemo { 
    public static void main(String[] args) throws FileNotFoundException { 
        // 记录开始时间 
        long start = System.currentTimeMillis(); 
        // 创建流对象 
        try (
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe")); 
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe")); 
        ){
            // 读写数据 int b; 
            while ((b = bis.read()) != ‐1) { 
                bos.write(b); 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
        // 记录结束时间 
        long end = System.currentTimeMillis(); 
        System.out.println("缓冲流复制时间:"+(end ‐ start)+" 毫秒"); 
    } 
}
缓冲流复制时间:8016 毫秒

3. 使用数组的方式(前面讲过)可以变得更快,代码如下:

public class BufferedDemo { 
    public static void main(String[] args) throws FileNotFoundException { 
        // 记录开始时间 
        long start = System.currentTimeMillis(); 
        // 创建流对象 
        try (
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("jdk9.exe")); 
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.exe")); 
        ){ 
            // 读写数据 
            int len;
            byte[] bytes = new byte[8*1024]; 
            while ((len = bis.read(bytes)) != ‐1) { 
            bos.write(bytes, 0 , len); 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
        // 记录结束时间 
        long end = System.currentTimeMillis(); 
        System.out.println("缓冲流使用数组复制时间:"+(end ‐ start)+" 毫秒"); 
    } 
}
缓冲流使用数组复制时间:666 毫秒

字符缓冲流

构造方法

  • public BufferedReader(Reader in) :创建一个 新的缓冲输入流。
  • public BufferedWriter(Writer out) : 创建一个新的缓冲输出流。

构造举例,代码如下:

// 创建字符缓冲输入流 
BufferedReader br = new BufferedReader(new FileReader("br.txt")); 
// 创建字符缓冲输出流 
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

特有方法

  字符缓冲流的基本方法与普通字符流调用方式一致,不再阐述,主要看看它们具备的特有方法:
  • BufferedReader: public String readLine() : 读一行文字。
  • BufferedWriter: public void newLine() : 写一行行分隔符,由系统属性定义符号。

readLine 方法演示,代码如下:

public class BufferedReaderDemo { 
    public static void main(String[] args) throws IOException { 
        // 创建流对象 
        BufferedReader br = new BufferedReader(new FileReader("in.txt")); 
        // 定义字符串,保存读取的一行文字 
        String line = null; 
        // 循环读取,读取到最后返回null 
        while ((line = br.readLine())!=null) { 
            System.out.print(line);  
        }
        // 释放资源 
        br.close(); 
    }
}

newLine 方法演示,代码如下:

public class BufferedWriterDemo throws IOException { 
    public static void main(String[] args) throws IOException {
        // 创建流对象 
        BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt")); 
        // 写出数据 
        bw.write("张三"); 
        // 写出换行 
        bw.newLine(); 
        bw.write("李四"); 
        bw.newLine(); 
        bw.write("王五"); 
        bw.newLine(); 
        // 释放资源 
        bw.close(); 
    } 
}
输出效果:
张三
李四
王五

转换流

概述

  先思考编码时会引出的一个问题:在IDEA中,使用 FileReader 读取项目中的文本文件。由于IDEA的设置,都是默认的 UTF-8 编码,所以没有任何问题。但是,当读取Windows系统中创建的文本文件时,由于Windows系统的默认是GBK编码,就会出现乱码。解决办法就用到了Java中的转换流,转换流是字节与字符间的桥梁,转换流理解图解如下:

字符编码和字符集

  • 字符编码 Character Encoding : 就是一套自然语言的字符与二进制数之间的对应规则。
  • 字符集 Charset :也叫编码表。是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。
计算机要准确的存储和识别各种字符集符号,需要进行字符编码,一套字符集必然至少有一套字符编码。常见字符集有ASCII字符集、GBK字符集、Unicode字符集等,均在以下列出供了解:

ASCII字符集 :

  基本的ASCII字符集,使用7位(bits)表示一个字符,共128字符。ASCII的扩展字符集使用8位(bits)表示一个字符,共256字符。

GBxxx字符集: 

  • GB2312:简体中文码表。一个小于127的字符的意义与原来相同。但两个大于127的字符连在一起时,就表示一个汉字,这样大约可以组合了包含7000多个简体汉字。
  • GBK:最常用的中文码表。是在GB2312标准基础上的扩展规范,使用了双字节编码方案,共收录了21003个汉字,完全兼容GB2312标准,同时支持繁体汉字以及日韩汉字等。
  • GB18030:最新的中文码表。收录汉字70244个,采用多字节编码,每个字可以由1个、2个或4个字节组成。支持中国国内少数民族的文字,同时支持繁体汉字以及日韩汉字等。

Unicode字符集 :

  它最多使用4个字节的数字来表达每个字母、符号,或者文字。有三种编码方案,UTF-8、UTF-16和UTF-32。最为常用的UTF-8编码。
  • UTF-8编码:可以用来表示Unicode标准中任何字符,编码规则:
  1. 128个US-ASCII字符,只需一个字节编码;
  2. 拉丁文等字符,需要二个字节编码;
  3. 大部分常用字(含中文),使用三个字节编码;
  4. 其他极少使用的Unicode辅助字符,使用四字节编码。

InputStreamReader类

  转换流 java.io.InputStreamReader ,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

  • InputStreamReader(InputStream in) : 创建一个使用默认字符集的字符流。
  • InputStreamReader(InputStream in, String charsetName) : 创建一个指定字符集的字符流。

构造举例,代码如下:

InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");

指定编码读取:

public class ReaderDemo { 
    public static void main(String[] args) throws IOException { 
        // 定义文件路径,文件为gbk编码 
        String FileName = "D:\\in_gbk.txt"; 
        // 创建流对象,默认UTF8编码 
        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName)); 
        // 创建流对象,指定GBK编码 
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
        // 定义变量,保存字符 
        int read; 
        // 使用默认编码字符流读取,乱码 
        while ((read = isr.read()) != ‐1) { 
            System.out.print((char)read); // ��Һ�
        }
        isr.close(); 
        // 使用指定编码字符流读取,正常解析 
        while ((read = isr2.read()) != ‐1) { 
            System.out.print((char)read);// 大家好 
        }
        isr2.close(); 
    } 
}

OutputStreamWriter类

  转换流 java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

  • OutputStreamWriter(OutputStream in) : 创建一个使用默认字符集的字符流。
  • OutputStreamWriter(OutputStream in, String charsetName) : 创建一个指定字符集的字符流。

构造举例,代码如下:

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

指定编码写出:

public class OutputDemo { 
    public static void main(String[] args) throws IOException { 
        // 定义文件路径 
        String FileName = "D:\\out.txt"; 
        // 创建流对象,默认UTF8编码 
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(FileName)); 
        // 写出数据 
        osw.write("你好"); // 保存为6个字节 
        osw.close();

        // 定义文件路径 
        String FileName2 = "E:\\out2.txt"; 
        // 创建流对象,指定GBK编码 
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(FileName2),"GBK"); 
        // 写出数据 
        osw2.write("你好");// 保存为4个字节 
        osw2.close(); 
    } 
}

序列化

概述

  Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该 对象的数据 、 对象的类型 和 对象中存储的属性 等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化。 对象的数据 、 对象的类型 和 对象中存储的数据 信息,都可以用来在内存中创建对象。看图理解序列化:

 

 

ObjectOutputStream类

  java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。

构造方法

  • public ObjectOutputStream(OutputStream out) : 创建一个指定OutputStream的ObjectOutputStream。

构造举例,代码如下:

FileOutputStream fileOut = new FileOutputStream("Students.txt"); 
ObjectOutputStream out = new ObjectOutputStream(fileOut);

序列化操作

  一个对象要想序列化,必须满足两个条件:
  • 该类必须实现 java.io.Serializable 接口, Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出 NotSerializableException 。
  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。

特有方法

  • public final void writeObject (Object obj) : 将指定的对象写出。

工具类:

public class Student implements java.io.Serializable { 
    public String name; //姓名
    public String address; //地址
    public transient int age; // transient瞬态修饰成员,不会被序列化 
    public Student(){}
    public Student(String name,String address,int age){
        this.name=name;
        this.address=address;
        this.age=age;
    }
}

测试类:

public class SerializeDemo{ 
    public static void main(String [] args) { 
       Student s = new Student("张三","北京","18"); try {
            // 创建序列化流对象 
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Students.txt")); 
            // 写出对象 
            oos.writeObject(s); 
            // 释放资源 
            oos.close(); 
            System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。 
        } catch(IOException i) { 
            i.printStackTrace(); 
        } 
    } 
}
输出结果: 
Serialized data is saved

ObjectInputStream类

  ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。

构造方法

  • public ObjectInputStream(InputStream in) : 创建一个指定InputStream的ObjectInputStream。

反序列化操作

  如果能找到一个对象的class文件,我们可以进行反序列化操作,调用 ObjectInputStream 读取对象的方法:
  • public final Object readObject () : 读取一个对象。
public class DeserializeDemo {
    public static void main(String [] args) { 
        Student s = null; 
        try {
            // 创建反序列化流 
            FileInputStream fileIn = new FileInputStream("Students.txt"); 
            ObjectInputStream in = new ObjectInputStream(fileIn); 
            // 读取一个对象 
            s = (Student) in.readObject(); 
            // 释放资源 
            in.close();
            fileIn.close(); 
        }catch(IOException i) { 
            // 捕获其他异常 
            i.printStackTrace(); 
            return; 
        }catch(ClassNotFoundException c) { 
            // 捕获类找不到异常 
            c.printStackTrace(); 
            return; 
        }
        // 无异常,直接打印输出 
        System.out.println("Name: " + e.name); // 张三
        System.out.println("Address: " + e.address); // 北京
        System.out.println("age: " + e.age); // 0 
    } 
}

注意:

  对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出一个ClassNotFoundException 异常。

另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个 InvalidClassException 异常。发生这个异常的原因如下:
  1. 该类的序列版本号与从流中读取的类描述符的版本号不匹配
  2. 该类包含未知数据类型
  3. 该类没有可访问的无参数构造方法

Serializable 接口给需要序列化的类,提供了一个序列版本号。 serialVersionUID 该版本号的目的在于验证序列化的对象和对应类是否版本匹配。

重定向

概述

  Java标准输入输出分别通过System.in和System.out来代表,默认情况下它们分别代表键盘和显示器;当程序通过System.in来获取输入时,实际上是从键盘读取输入;当程序试图通过System.out执行输出时,程序总是输出到屏幕。而重定向的意思就是改变系统规定流的流向,达到不同目的与效果。

PrintStream类

  平时我们在控制台打印输出,是调用 print 方法和 println 方法完成的,这两个方法都来自于java.io.PrintStream 类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。

构造方法

  • public PrintStream(String fileName) : 使用指定的文件名创建一个新的打印流。

构造举例,代码如下:

PrintStream ps = new PrintStream(new FileOutputStream("ps.txt"));

重定向标准输入/输出

在System类中提供了如下三个重定向标准输入输出的方法:

  • static void setIn(InputStream in):重定向“标准”输入流,将System.in重定向到指定文件,而不是键盘输入。

代码演示如下:

public class RedirectIn { 
    public static void main(String[] args) throws IOException { 
        FileInputSteam fis = new FileInputStream("RedirectIn.java");
        //将标准输入重定向到fis输入流
        System.setIn(fis);
        //使用System.in创建Scanner对象,用于获取标准输入
        Scanner sc = new Scanner(System.in);
        //增加下面一行只把回车作为分隔符
        sc.useDelimiter("\n");
        //判断是否还有下一个输入项
        while(sc.hasNext()){
            //输出输入项
            System.out.println(sc.next());
        }
    } 
}
  • static void setOut(PrintStream out):重定向“标准”输出流,将System.out的输出重定向到文件输出,而不是在屏幕上输出。

代码演示如下:

public class RedirectOut { 
    public static void main(String[] args) throws IOException { 
        // 调用系统的打印流,控制台直接输出97 
        System.out.println(97); 
        // 创建打印流,指定文件的名称 
        PrintStream ps = new PrintStream(new FileOutputStream("RedirectOut.txt")); 
        // 设置系统的打印流流向,输出到RedirectOut.txt 
        System.setOut(ps); 
        // 调用系统的打印流,RedirectOut.txt中输出97 
        System.out.println(97); 
    } 
}
  • static void setErr(PrintStream err):重定向“标准”错误输出流,与static void setOut(PrintStream out)同理。

 

posted @ 2020-12-03 20:44  A_xiba  阅读(115)  评论(0编辑  收藏  举报