Java IO流


IO就是输入输出。在java中,对数据的输入输出以“流(stream)”的方式进行,所以称为IO流。

(抽象基类) 字节流 字符流
输入流 InputStream Reader
输出流 OutputStream Writer

字节流就是以字节(byte)为单位传输的流,字符流就是以字符(char)为单位传输的流。

其它所有输入输出流的类都是上面4个抽象基类的子类。

节点流(文件流)

节点流就是直接在数据和程序之间进行传输数据的流,不作用于已有的流之上。作用于已有的流之上的流叫做缓冲流。

FileReader

字符流,用来读文本文件中的数据

注意点:

  1. 异常的处理:为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally处理
  2. 读入的文件一定要存在,否则会报FileNotFoundException

主要方法:FileReader.read(char[] cbuf): 返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1

public void testFileReader1() {
    FileReader fr = null;
    try {
        // 1. File类的实例化
        File file = new File("IO\\hello.txt");

        // 2. FileReader 流的实例化
        fr = new FileReader(file);

        // 3. 读入操作
        // read(char[] cbuf): 返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1
        char[] cbuf = new char[5];
        int len;
        while((len = fr.read(cbuf)) != -1) {
            String str = new String(cbuf, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fr != null)
        // 4. 资源的关闭
        try {
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileWriter

字符流,用于文本文件的写入操作

注意点:

  1. 输出操作,对应的File是可以不存在的,不会报异常
    1. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
    2. File对应的硬盘中的文件如果存在:
      1. 如果流使用的构造器是:FileWriter(file, false) / FileWriter(file): 对原有文件的覆盖
      2. 如果流使用的构造器是:FileWriter(file, true): 不会对原有文件覆盖,而是在原有文件基础上追加内容

主要方法:FileWriter.writer(char[] cbuf, int start, int len): 写出cbuf中的字符,从start位置开始写,每次写出len个字符

复制文本文件demo:

public void testFileReaderFileWriter() {
    FileReader fr = null;
    FileWriter fw = null;
    try {
        // 1. 创建File类的对象,指明读入和写出的文件
        File srcFile = new File("IO\\hello.txt");
        File destFile = new File("IO\\hello2.txt");

        // 2. 创建输入流和输出流的对象
        fr = new FileReader(srcFile);
        fw = new FileWriter(destFile);

        // 3. 数据的读入和写出操作
        char[] cbuf = new char[1024];
        int len;  // 记录每次读入到cbuf数组中的字符的个数
        while ((len = fr.read(cbuf)) != -1) {
            // 每次写出len个字符
            fw.write(cbuf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4. 关闭流资源
        try {
            if (fw != null)
                fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (fr != null)
                fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

FileInputStream

字节流,用于非文本文件的读取操作,用法与FileReader大致一样,只是传入read()的数组要由char[]改成byte[]

FileOutputStream

字节流,用于非文本文件的写入操作,用法与FileWriter大致一样,只是传入write()的数组要由char[]改成byte[]

复制任意格式文件demo:

// 指定路径下文件的复制
public void copyFile(String srcPath, String destPath) {
    FileInputStream fr = null;
    FileOutputStream fw = null;
    try {
        // 1. 创建File类的对象,指明读入和写出的文件
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);

        // 2. 创建输入流和输出流的对象
        fr = new FileInputStream(srcFile);
        fw = new FileOutputStream(destFile);

        // 3. 数据的读入和写出操作
        byte[] cbuf = new byte[1024];
        int len;  // 记录每次读入到cbuf数组中的字符的个数
        while ((len = fr.read(cbuf)) != -1) {
            // 每次写出len个字符
            fw.write(cbuf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 4. 关闭流资源
        try {
            if (fw != null)
                fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (fr != null)
                fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意点:

  1. 对于文本文件(.txt .java .c .cpp),使用字符流处理
  2. 对于非文本文件(.jpg .mp3 .mp4 .avi .doc .ppt ...),使用字节流处理
  3. 若用字节流读取文本文件内容并输出,则汉字可能会变成乱码
  4. 对于复制操作,字节流也可以用于复制文本文件,因此上面的demo虽然使用字节流但可以用于所有格式文件的复制

处理流

处理流:“套接”在已有的流的基础上的流。

缓冲流

缓冲流的作用:提高流的读取、写入的速度

提高读写速度的原因:内部提供了一个缓冲区

BufferedInputStream、BufferedOutputStream

用法与FileInputStream类和FileOutputStream类类似

用BufferedInputStream类、BufferedOutputStream类复制文件的demo:

// 实现文件复制的方法
public void copyFileWithBuffered(String srcPath, String destPath) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        // 1. 造文件
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        // 2. 造流
        // 2.1 造节点流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        // 2.2 造缓冲流
        bis = new BufferedInputStream(fis);
        bos = new BufferedOutputStream(fos);

        // 3. 复制的细节:读取、写入
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);

            //                bos.flush();  // 刷新缓冲区
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bos != null)
            // 4. 资源关闭
            // 关闭外层的流的同时,内层的流会自动关闭
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        if (bis != null)
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

其它方法:BufferedOutputStream.flush(): 将缓冲区内现有的内容写入文件然后刷新缓冲区。

BufferedReader、BufferedWriter

用法也与FileReader和FileWriter类似

新方法:BufferedReader.readLine(): 读取一行,不包括换行符

BufferedWriter.newLine(): 写一个空行

用BufferedReader和BufferedWriter复制文本文件的demo:

/*
使用BufferedReader和BufferedWriter实现文本文件的复制
*/
public void testBufferedReaderBufferedWriter() {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        //创建文件和响应的流
        br = new BufferedReader(new FileReader(new File("IO\\hello.txt")));
        bw = new BufferedWriter(new FileWriter(new File("IO\\hello4.txt")));

        // 读写操作
        String data;
        while ((data = br.readLine()) != null) {
            bw.write(data);  // data中不包含换行符
            bw.newLine();  // 提供换行的操作
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bw != null)
            // 关闭资源
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        if (br != null)
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

其它方法:BufferedWriter.flush(): 将缓冲区内现有的内容写入文件然后刷新缓冲区。

对象流

对象流的使用:

  1. 相关类:ObjectInputStream 和 ObjectOutputStream
  2. 对象流的作用:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处是可以通过序列化把Java中的对象写入到数据源中,也能通过反序列化把对象从数据源中还原回来。
  3. 一个Java对象可序列化的要求:
    1. 需要实现Serializable接口(该接口中没有方法需要实现,这种接口称为标识接口)
    2. 当前类提供一个全局常量:serialVersionUID
    3. 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)
  4. 对象的序列化机制:
    • 序列化:将内存中的Java对象转换成平台无关的二进制流,然后把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
    • 反序列化:当其它程序获取了这种二进制流,可以恢复成原来的Java对象。

关于serialVersionUID:

  • 凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:private static final long serialVersionUID,建议显式声明。
  • 简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地响应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
public static void testObjectOutputStream() {
    ObjectOutputStream oos = null;
    try {
        // 1.
        oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
        // 2.
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush();  // 刷新操作

        oos.writeObject(new Person("王明", 23));
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (oos != null)
            // 3.
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

/*
反序列化:将磁盘文件中的对象还原为内存中的Java对象
使用ObjectInputStream来实现
*/
public static void testObjectInputStream() {
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("object.dat"));

        Object obj = ois.readObject();
        String str = (String) obj;

        Person p = (Person) ois.readObject();

        System.out.println(str);
        System.out.println(p);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ois != null)
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

自定义类实现Serializable接口及提供全局常量serialVersionUID(这个serialVersionUID是long类型,值可随意写,别重复就行):

image-20220217100104976

注意:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量。

总结

IO流操作的一般流程:

  1. File类的实例化
  2. 流类的实例化
  3. 读写操作
  4. 流资源的关闭