IO流

IO简介

数据源

数据源 Data Source,提供数据的原始媒介。常见的数据源有:数据库、文件、其他程
序、内存、网络连接、IO 设备。
数据源分为:源设备、目标设备。

  • 源设备:为程序提供数据,一般对应输入流。
  • 目标设备:程序数据的目的地,一般对应输出流。

流的概念

流是一个抽象、动态的概念,是一连串连续动态的数据集合


输入/输出流的划分是相对程序而言的,并不是相对数据源

四大IO抽象类

  • InputStream
    此抽象类是表示字节输入流的所有类的父类。InputSteam 是一个抽象类,它不可以实例化。 数据的读取需要由它的子类来实现。根据节点的不同,它派生了不同的节点流子类。继承自 InputSteam 的流都是用于向程序中输入数据,且数据的单位为字节(8 bit)
    常用方法:
    • int read():读取一个字节的数据,并将字节的值作为 int 类型返回(0-255 之间的一个值)。如果未读出字节则返回-1(返回值为-1 表示读取结束)。
    • void close():关闭输入流对象,释放相关系统资源。
  • OutputStream
    此抽象类是表示字节输出流的所有类的父类。输出流接收输出字节并将这些字节发送到某个目的地。
    常用方法:
    • void write(int n):向目的地中写入一个字节。
    • void close():关闭输出流对象,释放相关系统资源。
  • Reader
    Reader 用于读取的字符流抽象类,数据单位为字符。
    常用方法:
    • int read(): 读取一个字符的数据,并将字符的值作为 int 类型返回(0-65535 之间的一个值,即 Unicode 值)。如果未读出字符则返回-1(返回值为-1 表示读取结束)。
    • void close() : 关闭流对象,释放相关系统资源
  • Writer
    Writer 用于输出的字符流抽象类,数据单位为字符。
    常用方法:
    • void write(int n): 向输出流中写入一个字符。
    • void close() : 关闭输出流对象,释放相关系统资源

流的概念细分

按流的方向分类
  • 输入流:数据流从数据源到程序(以 InputStream、Reader 结尾的流)
  • 输出流:数据流从程序到目的地(以 OutPutStream、Writer结尾的流)
按处理的数据单元分类
  • 字节流:以字节为单位获取数据,命名上以 Stream 结尾的流一般是字节流,如 FileInputStream、FileOutputStream。可以读写任意类型的文件
  • 字符流:以字符为单位获取数据,命名上以 Reader/Writer 结尾的流一般是字符流,如 FileReader、FileWriter。仅限于文本文件(使用记事本可以打开的文件)处理非英文方便
按处理对象不同分类
  • 节点流:可以直接从数据源或目的地读写数据,如 FileInputStream、FileReader、
    DataInputStream 等。
  • 处理流:不直接连接到数据源或目的地,是”处理流的流”。通过对其他流的处
    理提高程序的性能,如 BufferedInputStream、BufferedReader 等。处理流也叫
    包装流


节点流处于 IO 操作的第一线,所有操作必须通过它们进行;处理流可以对节点流进行包装,提高性能或提高程序的灵活性

IO流类的体系

File类

File类的作用

File 类是 Java 提供的针对磁盘中的文件或目录转换对象的包装类。一个 File 对象而可以
代表一个文件或目录,File 对象可以实现获取文件和目录属性等功能,可以实现对文件和目
录的创建,删除等功能。

File类的常用方法
针对文件操作
  • createNewFile():创建新文件。
  • delete():直接从磁盘上删除
  • exists():查询磁盘中的文件是否存在
  • getAbsolutePath():获取绝对路径
  • getPath():获取相对路径
  • getName():获取文件名 相当于调用了一个 toString 方法。
  • isFile():判断是否是文件
  • length():查看文件中的字节数
  • isHidden():测试文件是否被这个抽象路径名是一个隐藏文件
针对目录操作
  • exists():查询目录是否存在
  • isDirectory()判断当前路径是否为目录
  • mkdir():创建目录
  • getParentFile():获取当前目录的父级目录。
  • list():返回一个字符串数组,包含目录中的文件和目录的路径名。
  • listFiles:返回一个 File 数组,表示用此抽象路径名表示的目录中的文件

字节流

字节流复制文件

1、创建输入输出流
2、使用输入输出流复制文件
3、释放资源

使用文件字节流复制文件,中转站为一个字节

IOS1.FileCopy

package IOS1;

import java.io.*;

/**
 * 字节流单字节复制文件
 */
public class FileCopy {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        File file1 = new File("D:/Test/IO流/test.txt");
        File file2 = new File("D:/Test/IO流/testcp.txt");
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        //2、使用输入和输出流完成文件复制
        int n;  //定义一个中转站,记录读取的位置,-1即读取完毕
        n = fis.read();
        while(n!=-1){
            fos.write(n);

            n = fis.read();
        }
        //释放资源
        if(fos!=null){
            fos.close();
        }
        if(fis!=null){
            fis.close();
        }
    }

}

使用文件字节流复制文件,中转站为一个数组

IOS1.FileCopy2

package IOS1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 字节流数组复制文件
 */
public class FileCopy2 {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        File file1 = new File("D:/Test/IO流/test.txt");
        File file2 = new File("D:/Test/IO流/testcp2.txt");
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        //FileInputStream fis = new FileInputStream(new File("D:/Test/IO流/test.txt"));  //写法2
        //FileInputStream fis = new FileInputStream("D:/Test/IO流/testcp2.txt");   //写法3
        //FileOutputStream fos = new FileOutputStream(file2,true);  //true:追加  false:覆盖
        //2、使用输入和输出流完成文件复制
        byte[] buffer = new byte[1024];  //定义一个中转站,一次读1024到缓存区,可分多次读
        int len = fis.read(buffer);   // 将fis的内容读到buffer中并返回读取的字节数
        while(len!=-1){
            fos.write(buffer,0,len);    //  不设置长度的话直接就是buffer的长度
            System.out.println(len);
            len = fis.read();
        }
        //释放资源
        if(fos!=null){
            fos.close();
        }
        if(fis!=null){
            fis.close();
        }
    }

}

字符流

字符流单字节复制文件

IOS2.FileCopyByReader

package IOS2;

import java.io.*;

/**
 * 字符流单字节复制文件
 */
public class FileCopyByReader {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        Reader fr = new FileReader("D:/Test/IO流/test.txt");
        Writer fw = new FileWriter("D:/Test/IO流/testcpByReader.txt");
        //2、使用输入和输出流完成文件复制
        int n;  //定义一个中转站,记录读取的位置,-1即读取完
        n = fr.read();
        while(n!=-1){
            fw.write(n);

            n = fr.read();
        }
        //释放资源
        if(fw!=null){
            fw.close();
        }
        if(fr!=null){
            fr.close();
        }
    }

}

字符流数组复制文件

IOS2.FileCopyByReader2

package IOS2;

import java.io.*;

/**
 * 字符流数组复制文件
 */
public class FileCopyByReader2 {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        Reader fr = new FileReader("D:/Test/IO流/test.txt");
        Writer fw = new FileWriter("D:/Test/IO流/testcpByReader2.txt");
        //2、使用输入和输出流完成文件复制
        char[] buffer = new char[1024];  //定义一个中转站数组,每次最多可以读取1024,-1即读取完
        int len = fr.read(buffer);  //将读取到的内容放到数组buffer,返回读取到的长度
        while(len!=-1){
            fw.write(buffer,0,len);

            len = fr.read();
        }
        //释放资源
        if(fw!=null){
            fw.close();
        }
        if(fr!=null){
            fr.close();
        }
    }

}

缓冲流


先从中转站读取输入缓冲区,缓冲区没有数据则去源文件读取数据,一次最多可以读8192

字节流带有缓冲区单字节复制文件

IOS3.FileCopyByBuffer

package IOS3;

import java.io.*;

/**
 * 字节流带有缓冲区单字节复制文件
 */
public class FileCopyByBuffer {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        File file1 = new File("D:/Test/IO流/test.txt");
        File file2 = new File("D:/Test/IO流/testcpByBuffer.txt");
        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //2、使用输入和输出流完成文件复制
        int n;  //定义一个中转站,记录读取的位置,-1即读取完毕
        n = bis.read();
        while(n!=-1){
            bos.write(n);

            n = bis.read();
        }
        //释放资源
        if(bos!=null){
            bos.close();
        }
        if(bis!=null){
            bis.close();
        }
    }

}

关闭高层流即可,关闭高层流其实就是关闭底层流

缓冲流为什么可以提高查询的速度
引入了输入输出缓冲区,大大减少了读写硬盘的次数
如何刷新缓存区
1、bos.close();先刷新缓冲区再关闭资源
2、直接调用bos.flush()
3、缓冲区满,自动刷新

带有缓冲区字符流单字节复制文件

IOS4.FileCopyByBufferReader

package IOS4;

import java.io.*;

/**
 * 带有缓冲区字符流单字节复制文件
 */
public class FileCopyByBufferReader {
    public static void main(String[] args) throws IOException {
        // 1、创建输入输出流
        Reader fr = new FileReader("D:/Test/IO流/IO流.txt");
        Writer fw = new FileWriter("D:/Test/IO流/IO流cp.txt");
        BufferedReader br = new BufferedReader(fr);
        BufferedWriter bw = new BufferedWriter(fw);
        //2、使用输入和输出流完成文件复制
        String str = br.readLine();
        while(str!=null){
            bw.write(str);
            bw.newLine();
            str = br.readLine();
        }
        //释放资源
        if(bw!=null){
            bw.close();
        }
        if(br!=null){
            br.close();
        }
    }

}

bufferReader提供按行读readLine()
不同操作系统的换行符是不一样的,newLine可以读取该系统的换行符再写进文件

readLine()的原理

StringBuilder builder =new StringBuilder()
int n =br.read();
builder.append(char(n));
int n =br.read();
builder.append(char(n));
....
读到一行的末尾
builder.toStirng();

数据流

  • 只有字节流,没有字符流
  • 都是处理流,不是结点流
  • 数据流只能操作基本数据类型和字符串,对象流还可以操作对象
  • 写入的是二进制数据,无法通过记事本查看
  • 写入的数据需要使用对应的输入流来读取
    IOS5.TestDataInputStream
package IOS5;

import java.io.*;

public class TestDataInputStrem {
    public static void main(String[] args) throws IOException {
        //write();
        read();
    }
    public static void read() throws IOException {
        FileInputStream fis = new FileInputStream("D:/Test/IO流/TestDataInputStream.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        DataInputStream dis = new DataInputStream(bis);
        System.out.println(dis.readInt());
        System.out.println(dis.readDouble());
        System.out.println(dis.readUTF());
        System.out.println(dis.readBoolean());
    }
    public static void write() throws IOException {
        FileOutputStream fos = new FileOutputStream("D:/Test/IO流/TestDataInputStream.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        DataOutputStream dos = new DataOutputStream(bos);
        dos.writeInt(10);
        dos.writeDouble(3.14);
        dos.writeUTF("hello阿狸");
        dos.writeBoolean(true);

        dos.close();
    }
}

对象流

使用对象流读写引用数据类型的数据,需要相应类实现Serializable接口(implement Serializable),否则会提示异常,提示没有序列化

序列化会自动生成序列号,如果修改了类,序列号会发生改变,写后再改变再读就会使得序列号不一致读不了
local class incompatible: stream classdesc serialVersionUID = -7062043312128842776, local class serialVersionUID = 5404418922866025723
解决方法:固定一个序列号
1、打开idea的settings



2、搜索serialVersionUIID
3、勾选图中选项
4、apply
5、把鼠标放在类名处


注意:与其关联的类也要序列化

IOS5.Student

package IOS5;

import java.io.Serializable;

public class Student implements Serializable {
    private static final long serialVersionUID = 1042747756060817656L;
    private int id;
    private String name;
    private double score;

    public Student(int id, String name, double score) {
        this.id = id;
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}

IOS5.TestObjectInputStream

package IOS5;

import java.io.*;
import java.util.Date;

public class TestObjectInputStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write();
        read();
    }
    public static void read() throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream("D:/Test/IO流/TestObjectInputStream.txt");
        BufferedInputStream bis = new BufferedInputStream(fis);
        ObjectInputStream ois = new ObjectInputStream(bis);
        System.out.println(ois.readInt());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readObject());
        Student stu = (Student) ois.readObject();
        System.out.println(stu.toString());
        ois.close();
    }
    public static void write() throws IOException {
        FileOutputStream fos = new FileOutputStream("D:/Test/IO流/TestObjectInputStream.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeInt(10);
        oos.writeDouble(3.14);
        oos.writeUTF("hello阿狸");
        oos.writeBoolean(true);
        oos.writeObject(new Date());
        Student stu = new Student(1, "阿狸", 90);
        oos.writeObject(stu);
        oos.close();
    }
}

笔记来源于b站视频https://www.bilibili.com/video/BV1D54y1s7cj

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容