JavaSE--IO流

发布时间 2023-08-15 22:54:39作者: 洛小依ovo

一、IO流

1、IO流概述

  通过IO可以完成对硬盘文件的读和写

  从硬盘中读取文件,读到内存中:读(Read)、输入(Input)、输入流(InputStream)

  从内存中写入文件,写到硬盘中:写(Write)、输出(Output)、输出流(OutputStream)

  java.io.*;

2、IO流的分类

  1)一种方式是按照流的方向进行分类:

    以内存作为参照物。往内存中去,叫做输入(Input)。或者叫做读(Read);从内存中出来,叫做输出(Output)。或者叫做写(Write)

  2)另一种方式是按照读取数据方式不同进行分类:

    a)有的流是按照字节的方式读取数据,一次读取1个字节byte,等同于一次读取8个二进制位。

    这种流是万能的,什么类型的文件都可以读取。包括:文本文件,图片,声音文件,视频文件等....

假设文件file1.txt,采用字节流的话是这样读的:
a中国bc张三fe
第一次读:一个字节,正好读到'a'
第二次读:一个字节,正好读到'中'字符的一半。
第三次读:一个字节,正好读到'中'字符的另外一半。

    b)有的流是按照字符的方式读取数据的,一次读取一个字符,这种流是为了方便读取普通文本文件而存在的,这种流不能读取:图片、声音、视频等文件。只能读取纯文本文件,连word文件都无法读取

  假设文件file1.txt,采用字符流的话是这样读的:

a中国bc张三fe
第一次读:'a'字符('a'字符在windows系统中占用1个字节。)
第二次读:'中'字符('中'字符在windows系统中占用2个字节。)

综上所述:流的分类:输入流、输出流;字节流、字符流

3、java中IO流四大家族(都是抽象类)

  java.io.InputStream    字节输入流

  java.io.OutputStream      字节输出流

  java.io.Reader        字符输入流

  java.io.Writer         字符输出流

注意:在java中只要“类名”以Stream结尾的都是字节流。以“Reader/Writer”结尾的都是字符流。

  a)所有的流都实现了:

    java.io.Closeable接口,都是可关闭的,都有close()方法。

    流毕竟是一个管道,这个是内存和硬盘之间的通道,用完之后一定要关闭,不然会耗费(占用)很多资源。养成好习惯,用完流一定要关闭。

  b)所有的输出流都实现了:

    java.io.Flushable接口,都是可刷新的,都有flush()方法

    养成一个好习惯,输出流在最终输出之后,一定要记得flush(),刷新一下。这个刷新表示将通道/管道当中剩余未输出的数据强行输出完(清空管道)刷新的作用就是清空管道。

    注意:如果没有flush()可能会导致丢失数据。

4、需要掌握的流

  a)文件专属:

    java.io.FileInputStream(重点)

    java.io.FileOutputStream(重点)

    java.io.FileReader

    java.io.FileWriter

  b)转换流:(将字节流转换成字符流)

    java.io.InputStreamReader

    java.io.OutputStreamWriter

  c)缓冲流专属:

    java.io.BufferedReader

    java.io.BufferedWriter

    java.io.BufferedInputStream

    java.io.BufferedOutputStream

  d)数据流专属:

    java.io.DataInputStream

    java.io.DataOutputStream

  e)标准输出流:

    java.io.PrintWriter

    java.io.PrintStream(重点)

  f)对象专属流:

    java.io.ObjectInputStream(重点)

    java.io.ObjectOutputStream(重点)

二、文件专属

1、java.io.FileInputStream;字节输入流(重点)

  1)概述

    1)文件字节输入流,万能的,任何类型的文件都可以采用这个流来读

    2)字节的方式,完成输入的操作,完成读的操作(硬盘---> 内存)

  2)常用方法

    a)int read()一次读取一个字节

public class FileInputStreamTest01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            //FileInputStream fis = new FileInputStream("D:\\temp");
            fis = new FileInputStream("D:/temp");
            
            int readData = 0;
            while((readData = fis.read()) != -1){
                System.out.println(readData);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 在finally语句块当中确保流一定关闭。
            if (fis != null) { // 避免空指针异常!
                // 关闭流的前提是:流不是空。流是null的时候没必要关闭。
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

    b)int read(byte[] b)一次读取b.length个字节

      减少硬盘和内存交互,提高程序效率

public class FileInputStreamTest04 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("src/tempfile");
            // 准备一个byte数组
            byte[] bytes = new byte[4];

            int readCount = 0;
            while((readCount = fis.read(bytes)) != -1) {
                // 把byte数组转换成字符串,读到多少个转换多少个
                System.out.print(new String(bytes, 0, readCount));
            }

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

    c)int available()返回流当中剩余的没有读到的字节数量

FileInputStream fis = null;

fis = new FileInputStream("tempfile");
System.out.println("总字节数量:" + fis.available());
// 这个方法有什么用
// 这种方式不太适合太大的文件,因为byte[]数组不能太大。
byte[] bytes = new byte[fis.available()]; 
// 不需要循环了
// 直接读一次就行了
int readCount = fis.read(bytes);
System.out.println(new String(bytes));

    d)long skip(long n)跳过几个字节不读

// skip跳过几个字节不读取
fis.skip(3);
System.out.println(fis.read());

 2、java.io.FileOutputStream;字节输出流(重点)

  1)概述

    文件字节输出流,负责写。从内存到硬盘

  2)常用方法

    a)new FileOutputStream(文件路径)

    b)new FileOutputStream(文件路径,true/false); 参数为true则是追加方式

    c) fos.write(byte[] b); 数组中的全部写入

    d)fos.write(byte[] b, 0, 2); 写入数组中的一部分

public class FileOutputStreamTest01 {
    public static void main(String[] args) {
        FileOutputStream fos = null;
        try {
            // myfile文件不存在的时候会自动新建!
            // 这种方式谨慎使用,这种方式会先将原文件清空,然后重新写入。
            //fos = new FileOutputStream("myfile");
            //fos = new FileOutputStream(/src/tempfile");

            // 以追加的方式在文件末尾写入。不会清空原文件内容。
            fos = new FileOutputStream("/src/tempfile3", true);
            // 开始写。
            byte[] bytes = {97, 98, 99, 100};
            // 将byte数组全部写出!
            fos.write(bytes); // abcd
            // 将byte数组的一部分写出
            fos.write(bytes, 0, 2); // 再写出ab

            // 字符串
            String s = "好好啊好号";
            // 将字符串转换成byte数组。
            byte[] bs = s.getBytes();
            // 写
            fos.write(bs);

            // 写完之后,最后一定要刷新
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

   3)文件复制

public class Copy01 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            // 创建一个输入流对象
            fis = new FileInputStream("D:\\JavaSE-001.avi");
            // 创建一个输出流对象
            fos = new FileOutputStream("C:\\JavaSE-001.avi");

            // 最核心的:一边读,一边写
            byte[] bytes = new byte[1024 * 1024];
            int readCount = 0;
            while((readCount = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, readCount);
            }

            // 刷新,输出流最后要刷新
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 分开try,不要一起try。
            // 一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3、FileReader字符输入流

  1)概述

    文件字符输入流,只能读取普通文本

    读取文本内容时,比较方便,快捷

  2)常用方法

public class FileReaderTest {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            // 创建文件字符输入流
            reader = new FileReader("tempfile");

            // 开始读
            char[] chars = new char[4]; // 一次读取4个字符
            int readCount = 0;
            while((readCount = reader.read(chars)) != -1) {
                System.out.print(new String(chars,0,readCount));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

4、FileWriter字符输出流

  1)概述

    文件字符输出流。写。只能输出普通文本。

  2)常用方法

public class FileWriterTest {
    public static void main(String[] args) {
        FileWriter out = null;
        try {
            // 创建文件字符输出流对象
            //out = new FileWriter("file");
            // 追加方式
            out = new FileWriter("file", true);

            // 开始写。
            char[] chars = {'大','家','好','哈','哈'};
            out.write(chars);
            out.write(chars, 2, 3);

            out.write("我是一名java软件工程师!");
            // 写出一个换行符。
            out.write("\n");
            out.write("hello world!");

            // 刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  3)普通文件复制

public class Copy02 {
    public static void main(String[] args) {
        FileReader in = null;
        FileWriter out = null;
        try {
            in = new FileReader("chapter23/src/com/bjpowernode/java/io/Copy02.java");
            out = new FileWriter("Copy02.java");

            char[] chars = new char[1024 * 512];
            int readCount = 0;
            while((readCount = in.read(chars)) != -1){
                out.write(chars, 0, readCount);
            }
            // 刷新
            out.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

三、缓冲流专属

1、BufferedReader

  1)概述

    带有缓冲区的字符输入流

    使用这个流的时候不需要自定义char数组,或者不需要自定义byte数组。自带缓冲

  2)例子

// 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
// 外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
// 像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
FileReader reader = new FileReader("Copy02.txt");
BufferedReader br = new BufferedReader(reader);

// br.readLine()方法读取一个文本行,但不带换行符
String s = null;
while((s = br.readLine()) != null){
    System.out.print(s);
}

// 关闭流
// 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭
br.close();

  3)节点流和包装流

当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
FileReader reader = new FileReader("Copy02.txt");// 节点流
BufferedReader br = new BufferedReader(reader);// 包装流
关闭流时只需要关闭包装流,节点流内部会自动关闭

2、BufferedWriter

带有缓冲的字符输出流

BufferedWriter out = new BufferedWriter(new FileWriter("copy"));
// 开始写
out.write("hello world!");
out.write("\n");
out.write("hello kitty!");
// 刷新
out.flush();
// 关闭最外层
out.close();

四、转换流

1、InputStreamReader

/*
// 字节流
FileInputStream in = new FileInputStream("Copy02.txt");
// 通过转换流转换(InputStreamReader将字节流转换成字符流。)
// in是节点流。reader是包装流。
InputStreamReader reader = new InputStreamReader(in);
// 这个构造方法只能传一个字符流。不能传字节流。
// reader是节点流。br是包装流。
BufferedReader br = new BufferedReader(reader);
*/
// 合并
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("Copy02.txt")));
String line = null;
while((line = br.readLine()) != null){
    System.out.println(line);
}

// 关闭最外层
br.close();

 2、InputStreamWriter

// 两个包装流。两个节点流。相对来说
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("copy", true)));

out.write("hello world!");
out.write("\n");
out.write("hello kitty!");
out.flush();
out.close();

五、数据专属的流

1、java.io.DataOutputStream

  1)概述

    这个流可以将数据连同数据的类型一并写入文件。

    注意:这个文件不是普通文本文档。(这个文件使用记事本打不开。)

  2)例子

// 创建数据专属的字节输出流
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data"));
// 写数据
byte b = 100;
short s = 200;
int i = 300;
long l = 400L;
float f = 3.0F;
double d = 3.14;
boolean sex = false;
char c = 'a';
dos.writeByte(b); // 把数据以及数据的类型一并写入到文件当中
dos.writeShort(s);
dos.writeInt(i);
dos.writeLong(l);
dos.writeFloat(f);
dos.writeDouble(d);
dos.writeBoolean(sex);
dos.writeChar(c);

dos.flush();
dos.close();

2、java.io.DataInputStream

  1)概述

    DataOutputStream写的文件,只能使用DataInputStream去读

    并且读的时候你需要提前知道写入的顺序。读的顺序需要和写的顺序一致。才可以正常取出数据

  2)例子

DataInputStream dis = new DataInputStream(new FileInputStream("data"));
// 开始读
byte b = dis.readByte();
short s = dis.readShort();
int i = dis.readInt();
long l = dis.readLong();
float f = dis.readFloat();
double d = dis.readDouble();
boolean sex = dis.readBoolean();
char c = dis.readChar();

System.out.println(b);
System.out.println(s);
System.out.println(i + 1000);
System.out.println(l);
System.out.println(f);
System.out.println(d);
System.out.println(sex);
System.out.println(c);

dis.close();

六、标准输出流(重点)

1、概述

  java.io.PrintStream:标准的字节输出流。默认输出到控制台

  标准输出流不需要手动close()关闭

2、例子

// 联合起来写
System.out.println("hello world!");
// 分开写
PrintStream ps = System.out;
ps.println("hello zhangsan");

 3、改变标准输出流的方向

// 改变标准输出流的输出方向
// 标准输出流不再指向控制台,指向“log.txt”文件
PrintStream printStream = new PrintStream(new FileOutputStream("log.txt"));
// 修改输出方向,将输出方向修改到"log.txt"文件。
System.setOut(printStream);
// 再输出
System.out.println("hello world");
System.out.println("hello kitty");
System.out.println("hello zhangsan");

七、对象专属流(重点)

1、对象的序列化与反序列化

  参与序列化和反序列化的对象,必须实现Serializable接口

    注意:Serializable接口只是一个表示接口,这个接口当中什么代码都没有

// 这个接口的作用
起到标识的作用,标志的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇
Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号

2、对象的序列化

// 创建java对象
Student s = new Student(1111, "zhangsan");
// 序列化
    // 生成students文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));

// 序列化对象
oos.writeObject(s);

// 刷新
oos.flush();
// 关闭
oos.close();

3、反序列化

// 反序列化
// 获取到这个文件
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));
// 开始反序列化,读
Object obj = ois.readObject();
// 反序列化回来是一个学生对象,所以会调用学生对象的toString方法
System.out.println(obj);
ois.close();

4、一次性序列化多个对象

  把对象放到集合中,序列化集合。。当然这里参与序列化的ArrayList集合也要实现java.io.Serializable接口

// 序列化集合
List<User> userList = new ArrayList<>();
userList.add(new User(1,"zhangsan"));
userList.add(new User(2, "lisi"));
userList.add(new User(3, "wangwu"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));

// 序列化一个集合,这个集合对象中放了很多其他对象
oos.writeObject(userList);

oos.flush();
oos.close();
// 反序列化集合
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
List<User> userList = (List<User>)ois.readObject();
for(User user : userList){
    System.out.println(user);
}
ois.close();

5、transient关键字

  如果你不想让对象中的某个属性参与序列化,可以加上这个关键字,他就不会参与序列化

6、序列化版本号

  1)序列化版本号概述

    Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。如果没有手动写出来, java虚拟机会默认提供这个序列化版本号。但是如果不写的话是看不见的

    建议将序列化版本号手动的写出来。不建议自动生成

// 对象中自己写入序列化版本号
private static final long serialVersionUID = 1L;
// idea也可以自动生成
setting-->Inspections-->Serializable class without serialVersionUID
然后在实现了Serializable这个的类上右键生成就可以

  2)序列化版本号的作用

    a)java语言中区分类的机制

1首先通过类名进行比对,如果类名不一样,肯定不是同一个类
2如果类名一样,靠序列化版本号进行区分

    b)自动生成序列化版本号的优势与缺点

// 优势
如果有人编写了同一个名字的类,
对于java虚拟机来说,java虚拟机是可以区分开这两个类的,因为这两个类都实现了Serializable接口,
都有默认的序列化版本号,他们的序列化版本号不一样。所以区分开了
// 缺点
一旦代码确定之后,不能进行后续的修改,
因为只要修改,必然会重新编译,此时会生成全新的序列化版本号,这个时候java虚拟机会认为这是一个全新的类

    c)序列化版本号结论

凡是一个类实现了Serializable接口,建议给该类提供一个固定不变的序列化版本号
这样以后这个类即使代码修改了,但是版本号不变,java虚拟机会认为是同一个类

八、File类

1、概述

  File类和四大交租没有关系,所以File类不能完成对文件的读和写

  File对象是文件或者路径名的抽象表示形式。例如: C:\Drivers 这是一个File对象或者C:\Drivers\Lan\Realtek\Readme.txt 也是File对象。

  一个File对象有可能对应的是目录,也可能是文件。

2、File类中常用方法

  1)File类构造方法

// 传入一个路径名
File f1 = new File("D:\\file");
File f2 = new File("D:/a/b/c/d/e/f");

  2)判断文件或文件夹是否存在

f1.exists();

  3)创建创建新文件

// 如果D:\file不存在,则以文件的形式创建出来
if(!f1.exists()) {
    // 以文件形式新建
    f1.createNewFile();
}

  4)创建目录

// 如果D:\file不存在,则以目录的形式创建出来
if(!f1.exists()) {
    // 以目录的形式新建
    f1.mkdir();
}
// 创建多重目录
File f2 = new File("D:/a/b/c/d/e/f");
if(!f2.exists()) {
    // 多重目录的形式新建。
    f2.mkdirs();
}

  5)获取文件的父路径

File f3 = new File("D:\\course\\copy.txt");
// 获取文件的父路径
// 这个返回值是String
String parentPath = f3.getParent();
System.out.println(parentPath); //D:\course

// 这个返回值是File
File parentFile = f3.getParentFile();
// getAbsolutePath获取绝对路径
System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());

  6)获取文件名

File f1 = new File("D:\\course\\第一ppt模板.ppt");
// 获取文件名
System.out.println("文件名:" + f1.getName());

  7)判断是否是一个目录

f1.isDirectory();

  8)判断是否是一个文件

// 判断是否是一个文件
System.out.println(f1.isFile());

  9)获取文件最后一次修改时间

// 获取文件最后一次修改时间
long haoMiao = f1.lastModified(); // 这个毫秒是从1970年到现在的总毫秒数
// 将总毫秒数转换成日期
Date time = new Date(haoMiao);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(time);
System.out.println(strTime);

  10)获取文件大小

// 获取文件大小
System.out.println(f1.length());// 字节

  11)获取当前目录下的所有的子文件

// File[] listFiles()
// 获取当前目录下所有的子文件
File f = new File("D:\\course");
File[] files = f.listFiles();
// foreach
for(File file : files){
    //System.out.println(file.getAbsolutePath());// 绝对路径
    System.out.println(file.getName());// 文件名
}

 

九、IO与Properties联合使用

  设计机制:经常改变的数据,可以单独写一个文件,使用程序动态读取,只需要修改这个文件中的内容,java代码不需要改动,不需要重新编译,服务器也不需要重新启动,就可以拿到动态的数据

  类似于以上机制的这种文件称为配置文件,

  内容格式为key1=value key2=value,我们把这种配置文件叫做属性配置文件

  java规范要求:属性配置文件建议以.properties结尾,但是不是必须的

#userinfo.properties文件
username=admin
password=123
#等号前后最好不要有空格
/*
Properties是一个Map集合,key和value都是String类型。将userinfo文件中的数据加载到Properties对象当中。
*/
// 新建一个输入流对象
FileReader reader = new FileReader("chapter23/userinfo.properties");
// 新建一个Map集合
Properties pro = new Properties();

// 调用Properties对象的load方法将文件中的数据加载到Map集合中。
pro.load(reader); // 文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,右边做value

// 通过key来获取value
String username = pro.getProperty("username");
System.out.println(username);

String password = pro.getProperty("password");
System.out.println(password);