IO流专题 字符流 字节流 节点流 处理流

297 阅读16分钟

一、文件

1.什么是文件

文件是保存数据的地方,比如word 文档,txt文件,excel文件等等,它既可以保存一张图片、也可以保存视频、音频等等。

2.文件流

文件在程序中是以流的形式来操作的。

流:数据在数据源(比如文件)和程序(内存)之间经历的路径。

输入流:数据从数据源(文件)到程序(内存)的路径。

输出流:数据从程序(内存)到数据源(文件)的路径。

3.常用的文件操作

创建文件对象相关构造器和方法

new File(String pathname);                  // 根据路径构建一个 File 对象
new File(File parent, String child);        // 根据父目录文件 + 子路径构建
new File(String parent, String child);      // 根据父目录 + 子路径构建// 创建新文件
createNewFile       

File 类实现了 SerializableCompareable 接口。

4.获取文件的相关信息

public void info() {
    // 先创建文件对象
    File file = new File("d:\news1.txt");
​
    // 调用相应的方法,得到对应的信息
    System.out.println("文件存不存在 = " + file.exists());
    System.out.println("是不是一个文件 = " + file.isFile());
    System.out.println("是不是一个目录 = " + file.isDirectory());
    System.out.println("文件名字 = " + file.getName());
    System.out.println("文件绝对路径 = " + file.getAbsolutePath());
    System.out.println("文件父级目录 = " + file.getParent());
​
    // 一个中文占3个字节,一个英文占一个字节
    System.out.println("文件大小(字节) = " + file.length());
}

5.目录操作和文件删除

mkdir 创建一级目录、mkdirs 创建多级目录、delete 删除空目录或文件。

二、IO 流原理和分类

1.原理

I/OInput/Output 的缩写,I/O 技术是非常实用的技术,用于处理数据传输。如 读/写文件,网络通讯等。

Java 程序中,对于数据的 输入/输出操作以 “流(stream)” 的方式进行。

java.io 包下提供了各种 “流” 的类和接口,用以获取不同种类的数据,并通过方法输入或输出数据。

输入 input :读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。

输出 output :将程序(内存)数据输出到磁盘、光盘等存储设备中。

2.流的分类

按操作数据单位不同分为:字节流(8 bit,适用于二进制文件),字符流(一个字符对应 n 个字节,由字符编码决定)。

按数据流的流向不同分为:输入流、输出流。

按流的角色的不同分为:节点流,处理流 / 包装流

抽象基类字节流字符流
输入流InputStreamReader
输出流OutputStreamWriter

(1)JavaIO 流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。

(2)由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。

三、常用的类

1.InputStream 字节输入流

InputStream 抽象类是所有类字节输入流的超类,常用的子类有:

  1. FileInputStream :文件输入流
  2. BufferedInputStream:缓存字节输入流
  3. ObjectInputStream :对象字节输入流

实例一:FileInputStream

要求:请使用 FileInputStream 读取 hello.txt 文件,并将文件内容显示到控制台

@Test
public void readFile2() {
    String filePath = "d:\hello.txt";
    int readLen = 0;
    byte[] buf = new byte[8];                   // 一次读取8个字节
    FileInputStream fileInputStream = null;
    try {
        // 创建 FileInputStream 对象,用于读取文件
        fileInputStream = new FileInputStream(filePath);
​
        // 从输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
        // 如果返回-1,表示读取完毕,如果读取正常,返回实际读取的字节数
        while((readLen = fileInputStream.read(buf)) != -1) {
            System.out.print(new String(buf, 0, readLen));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭文件流
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实例二:FileOutputStream

要求:请使用 FileOutputStreama.txt 文件中写入 hello,world,如果文件不存在,会创建文件。(注意:前提是目录已经存在)。

@Test
public void writeFile() {
    // 创建 FileOutputStream 对象
    String filePath = "d:\a.txt";
    FileOutputStream fileOutputStream = null;
​
    try {
        // 设置为true,表示追加数据到文件
        fileOutputStream = new FileOutputStream(filePath, true);
        // 写入一个字节
        fileOutputStream.write('H');
        // 写入字符串
        String str = "hello,world!";
        fileOutputStream.write(str.getBytes());
        // fileOutputStream.write(str.getBytes(), 0, 3); //左闭右开
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

2.文件拷贝

要求:完成文件拷贝,将 d:\a.txt 拷贝到 d:\b.txt

/**
 * 思路:
 * 1. 创建文件的输入流,将文件读入到程序
 * 2. 创建文件的输出流,将读取到的文件数据,写入到指定的文件
 */
@Test
public void fileCopy() {
    String srcFilePath = "d:\a.txt";
    String destFilePath = "d:\b.txt";
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
​
    try {
        fileInputStream = new FileInputStream(srcFilePath);
        fileOutputStream = new FileOutputStream(destFilePath);
​
        //定义一个字节数组,提高读取效果
        byte[] buf = new byte[1024];
        int readLen = 0;
        while ((readLen = fileInputStream.read(buf)) != -1) {
            // 读取后,就写入文件,通过 fileOutputStream,一边读一边写
            // 必须添加长度,否则可能会出错
            fileOutputStream.write(buf, 0, readLen);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fileInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.文件字符流说明

FileReadFileWriter 是字符流,即按照字符来操作 IO

(1)FileReader 相关方法:

new FileReader(File/String)

read :每次读取单个字符,返回该字符,如果到文件末尾返回 -1

read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果到文件末尾返回 -1。

相关 API

new String(char[]) :将 char[] 转换成 String

new String(char[], off, len):将 char[] 的指定部分转换成 String

(2)FileWriter 常用方法

new FileWriter(File/String):覆盖模式,相当于流的指针在首段

new FileWriter(File/String, true):追加模式,相当于流的指针在尾端

write(int):写入单个字符

write(char[]):写入指定数组

write(char[], off, len):写入指定数组的指定部分

write(string):写入整个字符串

write(string, off, len):写入字符串的指定部分

相关API

String 类:toCharArray:将 String 转换成 char[]

注意:FileWriter 使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件。

4.FileReader 使用实例

要求:使用FileReader 读取文件内容,并显示

public void read(){
    String filePath = "d:\a.txt";
    int data = 0;
​
    try (FileReader fileReader = new FileReader(filePath)){
​
        /**
        // 单个字符读取文件
        while ((data = fileReader.read()) != -1) {
            System.out.print((char)data);
        }
        */
​
        // 使用 read(buf),返回的是实际读取到的字符数,如果返回-1,表示读文件结束
        int readLen = 0;
        char[] buf = new char[8];
        while ((readLen = fileReader.read(buf)) != -1) {
            System.out.print(new String(buf, 0, readLen));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

5.FileWriter 使用实例

要求:使用FileWriter 将 “现代操作系统” 写入 a.txt 文件中。

注意:FileWriter 使用后,必须要关闭(close)或刷新(flush),否则写入不到指定的文件。

public static void main(String[] args) {
    String filePath = "d:\a.txt";
​
    // 参数为 true,表示追加
    try (FileWriter fileWriter = new FileWriter(filePath, true)) {
        // 1.写入单个字符
        fileWriter.write('H');
​
        // 2.写入指定数组:write(char[])
        char[] chars = {'1', '2', '3'};
        fileWriter.write(chars);
​
        // 3.写入指定数组的指定部分,左闭右开
        fileWriter.write("现代操作系统黑皮书".toCharArray(), 0, 6);
​
        // 4.写入整个字符串
        fileWriter.write(" 你好广东");
​
        // 5. 写入字符串的指定部分,左闭右开
        fileWriter.write("1234", 0, 2);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

四、节点流和处理流

1.概念

(1)节点流可以从一个特定的数据源读写数据,如 FileReaderFileWriter 的数据源是文件。

(2)处理流(也叫包装流)是 “连接” 在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写能力,如 BufferedReaderBufferedWriter

数据源:存放数据的地方,可以是文件、数组、字符串、管道。

BufferedReader 类中,有属性 Reader,即可以封装一个节点流,该节点流可以是任意的,只要是 Reader 子类。

2.区别和联系

节点流是底层流/低级流,字节跟数据源相接。

处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。

处理流对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连。

3.处理流的功能主要体现

性能的提高:主要以增加缓冲的方式来提高输入输出的效率;

操作的便捷:处理流可能提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活。

4.BufferedReader 处理流

是字符流,按照字符来读取数据,读取二进制文件可能会导致文件缺损;要操作字节流,可以使用BufferedInputStream 处理流;

关闭处理流,只需要关闭外层流(即包装流)即可。

案例:使用 BufferedReader 读取文本文件,并显示在控制台。

public static void main(String[] args) throws Exception{
    String filePath = "d:\a.txt";
​
    // 创建 BufferedReader
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
    // 按行读取,效率高,当返回null,表示文件读取完毕
    String line;
    while ((line = bufferedReader.readLine()) != null) {
        System.out.println(line);
    }
​
    // 关闭流,只需要关闭 BufferedReader,因为底层会自动的去关闭节点流
    bufferedReader.close();
}

5.BufferWriter 处理流

是字符流,按照字符来读取数据,读取二进制文件可能会导致文件缺损;要操作字节流,可以使用BufferedOutputStream 处理流

关闭处理流,只需要关闭外层流(即包装流)即可。

案例:使用BufferedWriter 将 “ Hello,乔治” ,写入到文件中。

public static void main(String[] args) throws Exception{
    String filePath = "d:\b.txt";
​
    // 创建 BufferedWriter
    // 1. new FileWriter(filePath, true) 表示以追加的方式写入
    // 2. new FileWriter(filePath) 表示以覆盖的方式写入
    BufferedWriter bufferedWriter = new BufferedWriter((new FileWriter(filePath)));
    bufferedWriter.write("hello");
    bufferedWriter.write("乔治");
    // 插入一个和系统相关的换行符
    bufferedWriter.newLine();
    bufferedWriter.write("我最帅");
​
    // 关闭外层流即可,底层关闭的是传入的 FileWriter
    bufferedWriter.close();
}

6.Buffered 拷贝案例

要求:综合使用 BufferedReaderBufferedWriter 完成文本文件拷贝。

public static void main(String[] args) throws FileNotFoundException, IOException {
    String srcFilePath = "d:\a.txt";
    String destFilePath = "d:\c.txt";
​
    BufferedReader br = new BufferedReader(new FileReader(srcFilePath));
    BufferedWriter bw = new BufferedWriter(new FileWriter(destFilePath));
    String line;
​
    while((line = br.readLine()) != null) {
        // 每读取一行,就写入目标文件,需要用newLine换行,readLine 读取一行,但是没有读取换行符
        bw.write(line);
        bw.newLine();
    }
​
    br.close();
    bw.close();
}

7.字节处理流拷贝

BufferedInputStream 是字节流,在创建 BufferedInputStream 时,会创建一个内部缓冲去数组;

BufferedOutputStream 是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统。

案例:编程完成 图片/音乐 的拷贝

public static void main(String[] args) throws FileNotFoundException, IOException {
    String srcFilePath = "d:\1.jpg";
    String destFilePath = "d:\2.jpg";
​
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFilePath));
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
​
    // 循环的读取文件,并写入到 destFilePath
    byte[] buff = new byte[1024];
    int readLen = 0;
​
    // 当返回 -1 时,就表示文件读取完毕
    while((readLen = bis.read(buff)) != -1) {
        bos.write(buff, 0, readLen);
    }
​
    // 数据写入磁盘是在关闭流才进行的
    bis.close();
    bos.close();
}

五、对象处理流

1.概念

对象流 ObjectInputStreamObjectOutputStream

功能:提供了对基本类型或对象类型的序列化和反序列化的方法

  • ObjectOutputStream 提供序列化功能;
  • ObjectInputStream 提供反序列化功能。

需求:

1、将 int num = 100 这个 int 数据保存到文件中,注意不是 100 数字,而是 int 100 ,并且,能够从文件中直接恢复 int 100

2、将 Dog dog = new Dog("小黄" , 3) 这个 dog 对象保存到文件中,并且能够从文件恢复;

上面的要求,就是能够将基本数据类型 或者 对象 进行序列化 和 反序列化操作

序列化和反序列化

  • 序列化就是在保存数据时,保存数据的值和数据类型
  • 反序列化就是在恢复数据时,恢复数据的值和数据类型

需要让某个对象作出序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:

Serializable            // 这是一个标记接口,没有方法(推荐)
Externalizable          // 该接口有方法需要实现,因此我们一般实现上面的 Serializable 接口

2.ObjectOutputStream

需求:保存序列化数据到文件里

public class Dog implements Serializable {
    private String name;
    private int age;
​
    public Dog(String name, int age) {
        this.name = name;
        this.age = age;
    }
​
    public String toString() {
        return name + " " + age;
    }
​
    public String getName() {
        return name;
    }
}
public class ObjectOutputStream_ {
    public static void main(String[] args) throws Exception{
        // 序列化后保存的文件格式,不是纯文本,而是按照它的个数来保存
        String filePath = "d:\a.txt";
        ObjectOutputStream oops = new ObjectOutputStream(new FileOutputStream(filePath));
​
        // 序列化数据到 d:\a.txt
        oops.writeInt(100);            // int -> Integer (实现了 Serializable)
        oops.writeBoolean(true);    // boolean -> Boolean (实现了 Serializable)
        oops.writeChar('a');        // char -> Character
        oops.writeDouble(9.5);      // double -> Double
        oops.writeUTF("我最帅");     // String 实现了 Serializable
        oops.writeObject(new Dog("旺财", 10));
​
        oops.close();
    }
}

3.ObjectInputStream

需求:反序列化读取数据

public class ObjectInputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 指定反序列化文件
        String filePath = "d:\a.txt";
​
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
​
        // 注意:读取反序列化的顺序需要和序列化保存数据的顺序一致
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
​
        // dog 的编译类型是 Object,dog 的运行类型是 Dog
        Object dog = ois.readObject();
        System.out.println("运行类型=" + dog.getClass());
        System.out.println("dog=" + dog);               // 底层 Object -> Dog
​
        // 需要特别注意的细节
        // 1. 如果我们希望调用 Dog 的方法,需要向下转型
        // 2. Dog 类的定义,我们需要可以引用到
        Dog dog2 = (Dog)dog;
        System.out.println(dog2.getName());
        
        // 关闭流,关闭外层流即可,底层会关闭 FileInputStream 流
        ois.close();
    }
}

4.使用细节

注意事项和细节说明

  1. 读写顺序要一致;
  2. 要实现序列化或反序列化对象,需要实现 Serializable
  3. 序列化的类中建议添加 SerialVersionUID,为了提高版本的兼容性;
  4. 序列化对象时,默认将里面所有属性都进行序列化,但除了 statictransient 修饰的成员;
  5. 序列化对象时,要求里面属性的类型也需要实现序列化接口;
  6. 序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化;

六、标准输入输出流

类型默认设备
System.in 标准输入InputStream键盘
System.out 标准输出PrintStream显示器
// System 类的 public final static InputStream in = null
// System.in 编译类型 InputStream
// System.in 运行类型 BufferedInputStream,属于处理流和字节流
// 表示标准输入:键盘
System.out.println(System.in.getClass());
​
//Scanner 是从标准输入(键盘)接收数据
Scanner sc = new Scanner(System.in);
​
// System.out public final static PrintStream out = null;
// 编译类型 PrintStream
// 运行类型 PrintStream
// 表示标准输出:显示器
System.out.println(System.out.getClass());

七、乱码引出转换流

InputStreamReaderReader 的子类,可以将InputStream (字节流)包装成 Reader字符流

OutputStreamWriterWriter 的子类,可以将 OutputStream (字节流)包装成 Writer (字符流)

当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流

可以在使用时指定编码格式(比如 utf-8gbkgbk2312ISO8859-1等)

案例一

将字节流 FileInputStream 包装成 字符流 InputStreamReader 对文件进行读取(按照 utf-8 / gbk格式) ,进而包装成 BufferedReader

public class InputStreamReader_ {
    public static void main(String[] args) throws Exception{
        String filePath = "d:\a.txt";
​
        // 把 FileInputStream 转成 InputStreamReader,指定编码 utf-8
        InputStreamReader ist = new InputStreamReader(new FileInputStream(filePath), "gbk");
​
        // 把 InputStreamReader 传入 BufferedReader
        BufferedReader br = new BufferedReader(ist);
​
        String s = br.readLine();
        System.out.println("读取的内容:" + s);
​
        // 关闭最外层的流即可,底层最终关闭的是 FileInputStream
        br.close();
    }
}

案例二:

将字节流 FileOutputStream 包装成 字符流 OutputStreamWriter,将文件进行写入(按照 gbk 格式,或指定其他,比如 utf-8

public static void main(String[] args) throws IOException, FileNotFoundException {
    String filePath = "d:\a.txt";
    String charSet = "gbk";
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
​
    osw.write("我最帅");
    osw.close();
}

八、打印流

打印流只有输出流,没有输入流:PrintStreamPrintWriter

1.PrintStream

public static void main(String[] args) throws FileNotFoundException {
    PrintStream out = System.out;
​
    // 默认情况下,PrintStream 输出数据的位置是标准输出,即显示器
    out.print("hello");
    out.close();
​
    // 我们可以去修改打印流输出的位置/设备
    System.setOut(new PrintStream("d:\a.txt"));
    System.out.print("输出到a.txt文件");
}

2.PrintWriter

public static void main(String[] args) throws  IOException {
    // 输出到控制台
    // PrintWriter printWriter = new PrintWriter(System.out);
    // 输出到文件
    PrintWriter printWriter = new PrintWriter(new FileWriter("d:\a.txt"));
    printWriter.print("hi, 你好");
    printWriter.close();
}

九、配置文件引出Properties

1.基本介绍

(1)专门用于读写配置文件的集合类,配置文件的格式:

键=值
键=值

(2)注意:键值对不需要有空格,值不需要用引号括起来。默认类型是 String

(3)Properties 的常见方法

  • load :加载配置文件的键值对到 Properties 对象;
  • list :将数据显示到指定设备;
  • getProperty(key):设置键值对到 Properties 对象中;
  • setProperty(key, value):设置键值对到 Properties 对象;
  • store:将 Properties 中的键值对存储到配置文件,在 idea 中,保存信息到配置文件,如果含有中文,会存储到 unicode 码。

实例一:读取配置文件

有一个配置文件mysql.properties,包含以下内容,编程读取ipuserpwd的值

ip=192.168.0.13
user=root
pwd=123456

实现

public static void main(String[] args) throws IOException {
    // 使用 Properties 类来读取 mysql.properties 文件
​
    // 1. 创建 Properties 对象
    Properties properties = new Properties();
    // 2. 加载指定配置文件
    properties.load(new FileReader("d:\mysql.properties"));
    // 3. 把K-V显示控制台
    properties.list(System.out);
    // 4. 根据key,获取对应的值
    String user = properties.getProperty("user");
    String pwd = properties.getProperty("pwd");
    System.out.println("用户名=" + user);
    System.out.println("密码=" + pwd);
}

实例二:添加键值对

使用 Properties 类添加 key-val 到新文件 mysql2.properties 中。

实现

public static void main(String[] args) throws FileNotFoundException, IOException {
    // 使用 Properties 类来创建配置文件,修改配置文件内容
​
    Properties properties= new Properties();
​
    // 创建
    properties.setProperty("Charset", "utf-8");
    properties.setProperty("user", "汤姆");               // 保存是,是中文的 unicode码值
    properties.setProperty("pwd", "abc111");
​
    // 将k-v 存储到文件中,第二个参数是注释
    properties.store(new FileOutputStream("src\mysql2.properties"), null);
    System.out.println("保存配置文件成功");
}

实例三:读取并修改键值对

使用 Properties 类完成对 mysql.properties 的读取,并修改某个 key-val

实现

public static void main(String[] args) throws FileNotFoundException, IOException {
    // 使用 Properties 类来创建配置文件,修改配置文件内容
​
    Properties properties= new Properties();
​
    // 创建
    // 1. 如果该文件没有 key,就是创建
    // 2. 如果该文件有key,就是修改
    properties.setProperty("Charset", "utf-8");
    properties.setProperty("user", "汤姆");               // 保存是,是中文的 unicode码值
    properties.setProperty("pwd", "abc123");
​
    // 将k-v 存储到文件中,第二个参数是注释
    properties.store(new FileOutputStream("src\mysql2.properties"), null);
    System.out.println("保存配置文件成功");
}

十、编程题

题一

判断 d 盘下是否有文件夹 mytemp,如果没有就创建 mytemp

d:\mytemp 目录下,创建文件 hello.txt

如果 hello.txt 文件已经存在,提示该文件已经存在,就不要再重复创建了

并且在 hello.txt 文件中,写入 hello, world~

public static void main(String[] args) throws IOException {
    String directoryPath = "d:\mytemp";
    File file = new File(directoryPath);
    if (!file.exists()) {
        // 创建
        if (file.mkdirs()) {
            System.out.println("创建 " + directoryPath + " 创建成功");
        } else {
            System.out.println("创建 " + directoryPath + " 失败");
        }
    }
​
    String filePath = directoryPath + "\hello.txt";
    file = new File(filePath);
    if (!file.exists()) {
        // 创建
        if (file.createNewFile()) {
            System.out.println(filePath + " 创建成功~");
​
            // 写入数据
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            bw.write("hello,word! 杰克");
            bw.close();
        } else {
            System.out.println(filePath + "创建失败~");
        }
    } else {
        // 如果文件已经存在,给出提示信息
        System.out.println(filePath + " 已经存在,不再重复创建...");
    }
}

题二

使用 BufferedReader 读取一个文本文件,为每行加上行号,再连通内容一并输出到屏幕上。注意中文乱码问题(提示:使用转换流)

public static void main(String[] args) throws FileNotFoundException, 
                            IOException,UnsupportedEncodingException {
    int linenum = 1;
    String filePath = "d:\a.txt";
    FileInputStream fis = new FileInputStream(filePath);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis, "gbk"));
    String line = br.readLine();
    while (line != null) {
        System.out.println(linenum++ + line);
        line = br.readLine();
    }
    br.close();
}

题三

编写一个 dog.properties文件,内容如下

name=tom
age=5
color=red

编写 Dog 类(name, age, color) 创建一个 dog 对象,读取 dog.properties 用相应的内容完成属性初始化,并序列化输出到dog.dat 文件。

// Dog 类
class Dog implements Serializable {
    private String name;
    private int age;
    private String color;
​
    public Dog (String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }
​
    public String toString() {
        return "name = " + name + " age= " + age + " color= " +color;
    }
}

实现

public static void main(String[] args) throws FileNotFoundException, IOException {
    Properties properties = new Properties();
    properties.load(new FileReader("src\dog.properties"));
    // 读取所有行,输出到控制台
    // properties.list(System.out);
    String name = properties.get("name") + "";
    int age = Integer.parseInt(properties.get("age") + "");
    String color = properties.get("color") + "";
​
    Dog dog = new Dog(name, age, color);
    System.out.println("==dog对象信息==");
    System.out.println(dog);
​
    // 将创建的 Dog 对象,序列化到文件 dog.dat
    String serFilePath = "d:\dog.dat";
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(serFilePath));
    oos.writeObject(dog);
​
    // 关闭流
    oos.close();
}

反序列化读取文件

public void m1() throws FileNotFoundException, IOException, ClassNotFoundException{
    String filePath = "d:\dog.dat";
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
    Object dog = ois.readObject();
    System.out.println(dog);
    ois.close();
}