Java核心API-IO流

输入和输出处理



前言

理解流的概念及分类,使用字节流读写文本文件,使用字符流读写文本文件


一、输入流和输出流

如何读写文件?通过流读写文件

​ 流是一组有序的数据序列

​ 以先进先出方式发送信息的通道

OutputStream类(抽象类)

InputStream类(抽象类)

Writer类(抽象类)

Reader类(抽象类)

1、FileInputStram类(InputStream类的子类)

构造方法

FileInputStream(File file): 通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定

FileInputStream(String name):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定

常用方法

在这里插入图片描述

public class FileInputStreamDemo01 {

    public static void main(String[] args) {

        // 创建FileInputStream类对象
        FileInputStream fileInputStream = null;

        File file = new File("D:/Java2408/aa.txt");
        try {
            // 创建FileInputStream类对象
            fileInputStream = new FileInputStream(file); // 传入file对象
            // 通过fileInputStream对象调用方法从指定的文件中读取

            // int available()返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数
            int available = fileInputStream.available();
            System.out.println("从指定的文件中大概能读取到的数据内容数量:" + available);

            //读取内容
            /*
            int num1 =fileInputStream.read();
            System.out.println((char)num1);

            int num2 =fileInputStream.read();
            System.out.println((char)num2);

            int num3 =fileInputStream.read();
            System.out.println((char)num3);

            int num4 =fileInputStream.read();
            System.out.println((char)num4);

            int num5 =fileInputStream.read();
            System.out.println((char)num5);

            int num6 =fileInputStream.read();
            System.out.println((char)num6);

            int num7 =fileInputStream.read();
            System.out.println((char)num7);

            int num8 =fileInputStream.read();
            System.out.println(num8);
            */

            /*while (fileInputStream.read()!=-1) {
                int num = fileInputStream.read();
                System.out.print((char)num + " "); // b d f h g l n p
            }*/
            // 上面的循环操作确实可以读取文件中的数据,但是会出现隔一个读取一个的情况
            // 因为在这里调用了两次read()方法,第一次只读取没有输出,第二次读取并输出

            int num;
            while ((num = fileInputStream.read()) != -1) {
                System.out.print((char) num + " ");
                // a b c d e f g h i g k l m n o p 
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 不管前面的操作中异常有没有或者有没有处理,流最终都要关闭
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamDemo02 {

    public static void main(String[] args) throws IOException {

        // 创建FileInputStream类对象
        FileInputStream fileInputStream = new FileInputStream("D:/Java2408/aa.txt");

        // 读取数据
        // int read(byte[] b)从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中
        // 读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1
        byte[] bytes = new byte[1024];
        int num = fileInputStream.read(bytes);
        System.out.println("从文件中读取的数据个数:" + num); // 从文件中读取的数据个数:16

        // 遍历数组,看文件中读取的数据是哪些
        /*for (int i = 0; i < bytes.length; i++) { i不再是小于数据长度
        遍历数组,数组里有内容的是下标0-6,在这里遍历所有元素,下标为7及之后的都为空,遍历只需要遍历读取到的数据
        }*/

        for (int i = 0; i < num; i++) {
            System.out.print((char) bytes[i] + " "); // a b c d e f g h i g k l m n o p
        }

        // 关闭流
        fileInputStream.close();

    }
}

2、FileOutputStream(OutputStream类的子类)

构造方法
在这里插入图片描述

常用方法

在这里插入图片描述

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

public class FileOutputStreamDemo01 {

    public static void main(String[] args) {

        // 创建FileOutputStream类对象
        FileOutputStream fileOutputStream = null;
        File file = new File("D:/Java2408/FileOutputStreamTest/a.txt");
        try {
            // FileOutputStream(File file)和FileOutputStream(String path)构造
            // 在写入数据时,写入的数据会覆盖文件中已经存在的数据
            fileOutputStream = new FileOutputStream(file);

            // 通过fileOutputStream对象调用方法将数据写入到指定文件中
            fileOutputStream.write(65);
            System.out.println("数据写入完毕");

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo02 {

    public static void main(String[] args) {

        // 创建FileOutputStream类对象
        FileOutputStream fileOutputStream = null;
        try {
            // FileOutputStream(String path,boolean flag)和FileOutputStream(File file,boolean flag)构造方法中的第二个参数用来标识写入的内容是否覆盖文件中原来已经存在的数据
            // 写false或者不写,都表示覆盖内容,如果写true,写入的内容写入到文件的末尾
            fileOutputStream = new FileOutputStream("D:/Java2408/FileOutputStreamTest/a.txt", true);
            // 通过fileOutputStream对象调用方法向指定文件中写入数据
            fileOutputStream.write(66);
            System.out.println("数据写入完毕");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo03 {

    public static void main(String[] args) throws IOException {

        // 创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件
        FileOutputStream fileOutputStream = new FileOutputStream("D:/Java2408/FileOutputStreamTest/c.txt");

        // 向指定文件中写入数据abcdefg
        String str = "abcdefg";
        // 将字符串转换成byte类型的数据
        byte[] bytes = str.getBytes();

        fileOutputStream.write(bytes);
        System.out.println("数据写入完毕");

    }
}

二、InputStreamReader类(Reader类的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.*;

public class InputStreamReaderDemo01 {

    public static void main(String[] args) {

        // 创建InputStreamReader类对象
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStream = new FileInputStream("D:/Java2408/InputStreamReader/a.txt");
            // InputStreamReader(InputStream in):创建一个使用默认字符集的 InputStreamReader。
            // InputStreamReader(InputStream in, String charsetName):创建使用指定字符集的 InputStreamReader
            inputStreamReader = new InputStreamReader(inputStream);
            // inputStreamReader = new InputStreamReader(inputStream,"GBK"); // 使用指定字符编码

            // 通过inputStreamReader对象调用方法读取数据
            // int num = inputStreamReader.read();
            int num;
            while ((num = inputStreamReader.read()) != -1) {
                System.out.print((char) num); // abcdefg
                // 如果文件内容有中文,可能出现乱码的情况
                // IDEA编码格式与文件编码格式一致,则不会乱码
                // System.out.println(System.getProperty("file.encoding"));获得本地平台的字符编码类型
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // IDEA平台编码
        System.out.println(System.getProperty("file.encoding")); // UTF-8

    }
}
import java.io.*;

public class InputStreamReaderDemo02 {

    public static void main(String[] args) {

        File file = new File("D:/Java2408/InputStreamReader/b.txt");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        try {
            inputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(inputStream, "GBK");

            // 读取数据,并将读取到的数据存储在char类型数组中
            char[] chars = new char[1024];
            int num = inputStreamReader.read(chars);

            // 遍历数组,输出数组中读取到的数据
            for (int i = 0; i < num; i++) {
                System.out.print(chars[i]); // abcdefg鏂板勾蹇箰
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        
    }
}

三、FileReader类(InputStreamReader类的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo01 {

    public static void main(String[] args) {

        // 创建FileReader类对象
        FileReader fileReader = null;
        try {
            // FileReader类只能按照平台的编码格式去读取文件中的数据,不能指定编码格式
            fileReader = new FileReader("D:\\Java2408\\FileReader\\b.txt"); // 文件内容abcdefg新年快乐

            // 通过fileReader对象调用方法读取数据
            // int num =fileReader.read();
            // System.out.println((char)num);
            int num;
            while ((num = fileReader.read()) != -1) {
                System.out.print((char) num); // abcdefg新年快乐
            }


        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}

四、BufferedReader类(Reader类的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.*;

public class BufferedReaderDemo01 {

    public static void main(String[] args) {

        // 创建BufferedReader类对象
        File file = new File("D:/Java2408/BufferedReader/b.txt");
        InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            inputStream = new FileInputStream(file);
            reader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(reader);

            // 通过bufferedReader对象读取数据
            // int num =bufferedReader.read();
            // System.out.println((char)num);

            //一行一行的读取数据
            /*
            String str1 =bufferedReader.readLine();
            System.out.println(str1);

            String str2 =bufferedReader.readLine();
            System.out.println(str2);

            String str3 =bufferedReader.readLine();
            System.out.println(str3);

            String str4 =bufferedReader.readLine();
            System.out.println(str4);

            String str5 =bufferedReader.readLine();
            System.out.println(str5);

            String str6 =bufferedReader.readLine();
            System.out.println(str6);

            上面的操作可以使用循环的方式来读取,只要读取的数据不为null,说明数据没有读取完,可以一直读
            while(bufferedReader.readLine()!=null){
                String str =bufferedReader.readLine();
                System.out.println(str);
            }
            */

            // 上面的读取操作会出现隔一行读一行,因为调用了2次readLine()方法,第一次判断读取的结果是否为null,第二次读取数据,我们需要读取数据后只要数据不为null,就输出
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                System.out.println(str);
                // abcdefg
                // 新年快乐
                // 恭喜发财
                // 顺风顺水
                // 万事如意
                // asdfg
            }

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

五、OutputStreamWriter类(Writer类的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.*;

public class OutputStreamWriterDemo01 {

    public static void main(String[] args) {

        //创建OutPutStreamWriter类对象
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStream = new FileOutputStream("D:/Java2408/OutputStreamWriter/a.txt", true);
            outputStreamWriter = new OutputStreamWriter(outputStream);

            //通过outputStreamWriter对象调用方法将数据写入到指定文件中
            // outputStreamWriter.write(65);
            // outputStreamWriter.write("qwertyuiop");
            outputStreamWriter.write("asdfghjkl", 1, 3);
            //此时数据还没有写入到文件中,因为数据还在缓冲中,需要使用方法将数据从缓冲里面传入到文件中
            outputStreamWriter.flush();

            System.out.println("数据写入完毕");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //多个流,后开的先关,先开的后关
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

六、FileWriter类(OutputStreamWriter的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo01 {

    public static void main(String[] args) {

        // 创建FileWriter类对象
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("D:/Java2408/FileWriter/a.txt", true);

            // 通过fileWriter对象调用方法将数据写入到文件中
            char[] chars = {'J', 'a', 'v', 'a', '2', '4', '0', '8'};
            fileWriter.write(chars);
            // 将缓冲中的数据刷新到文件中
            fileWriter.flush();

            System.out.println("数据写入完毕");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

七、BufferedWriter类(Writer类的子类)

1、构造方法

在这里插入图片描述

2、常用方法

在这里插入图片描述

import java.io.*;

public class BufferedWriterDemo01 {

    public static void main(String[] args) {

        // 创建BufferedWriter类对象
        OutputStream outputStream = null;
        Writer writer = null;
        BufferedWriter bufferedWriter = null;
        try {
            outputStream = new FileOutputStream("D:/Java2408/BufferedWriter/a.txt", true);
            writer = new OutputStreamWriter(outputStream, "UTF-8");
            bufferedWriter = new BufferedWriter(writer);

            // 通过bufferedWriter对象调用方法将数据写入指定文件中
            bufferedWriter.write("Java从入门到精通");
            bufferedWriter.write("Java从入门到放弃");
            // 写入一个换行分隔符
            bufferedWriter.newLine();
            bufferedWriter.write("Java从入门到精神病康复指南");
            bufferedWriter.newLine();
            bufferedWriter.write("Java是世界上最好的语言");
            bufferedWriter.flush();
            System.out.println("数据写入成功");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}

八、读写二进制文件

1、DataInputStream类(FilterInputStream的子类)

与FileInputStream类结合使用读取二进制文件

构造方法
在这里插入图片描述

常用方法

在这里插入图片描述

2、DtaOutputStream类(FilterOutputStream的子类)

与FileOutputStream类结合使用写入二进制文件

构造方法

在这里插入图片描述

常用方法

在这里插入图片描述

3、案例代码

import java.io.*;

public class DataInputStreamAndDataOutputStreamDemo01 {

    public static void main(String[] args) {

        // 创建DataInputStream类对象
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;

        OutputStream outputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            inputStream = new FileInputStream("D:/Java2408/Data/Car.jpg");
            dataInputStream = new DataInputStream(inputStream);

            // 创建二进制输出流
            outputStream = new FileOutputStream("D:/Java2408/Data/newCar.jpg");
            dataOutputStream = new DataOutputStream(outputStream);

            // 读取数据
            int num;
            while ((num = dataInputStream.read()) != -1) {
                // System.out.print(num+" ");
                // 读取到的是图片转换成的二进制数字(二进制数字转换成了十进制数字),输出没有意义,可以将读取到的数据再写入到另一个图片文件中
                // 将读取到的数据写入到指定文件中
                dataOutputStream.write(num);
            }

            System.out.println("图片复制完毕");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (dataInputStream != null) {
                try {
                    dataInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

九、序列化和反序列化

1、概念

序列化是将对象的状态写入到特定的流中的过程

反序列化则是从特定的流中获取数据重新构建对象的过程

2、ObjectInputStream类(InputStream类的子类)

构造方法

在这里插入图片描述

常用方法
在这里插入图片描述

3、ObjectOutputStream类(OutputStream类的子类)

构造方法
在这里插入图片描述

常用方法
在这里插入图片描述

4、案例代码

import java.io.Serializable;

public class Student implements Serializable {

    private String name;
    private int age;
    private char gender;

    public Student() {
    }

    public Student(String name, int age, char gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}
import java.io.*;

public class ObjectOutputStreamDemo01 {

    public static void main(String[] args) {

        // 创建一个Student类对象
        Student student = new Student("张三", 20, '男');

        // 将student对象写入到指定文件中
        // 创建ObjectOutputStream类对象
        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            outputStream = new FileOutputStream("D:\\Java2408\\Object\\student.txt");
            objectOutputStream = new ObjectOutputStream(outputStream);

            // 通过objectOutputStream对象调用方法将student对象写入到指定文件中
            objectOutputStream.writeObject(student);

            System.out.println("对象写入完毕");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
import java.io.*;

public class ObjectInputStreamDemo01 {

    public static void main(String[] args) {

        // 读取D盘中Java2408目录下student.txt文件中的对象信息

        // 创建ObjectInputStream类对象
        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            inputStream = new FileInputStream("D:/Java2408/Object/student.txt");
            objectInputStream = new ObjectInputStream(inputStream);

            // 通过objectInputStream对象调用方法从指定文件中读取对象信息
            Object object = objectInputStream.readObject();
            // 将object对象转换为其真实类型Student
            Student student = (Student) object;
            System.out.println(student); // Student{name='张三', age=20, gender=男}

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

创建多个对象存储在数组中

import java.io.*;

public class ObjectOutputStreamDemo02 {

    public static void main(String[] args) {

        // 创建3个Student对象
        Student student1 = new Student("张三", 22, '男');
        Student student2 = new Student("李四", 25, '男');
        Student student3 = new Student("王五", 29, '男');

        // 将这个三个Student类对象存储到数组或者集合中
        Student[] students = {student1, student2, student3};

        // 创建ObjectOutputStream类对象
        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            outputStream = new FileOutputStream("D:/Java2408/Object/students.txt");
            objectOutputStream = new ObjectOutputStream(outputStream);

            // 写入数据
            objectOutputStream.writeObject(students);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
import java.io.*;
import java.util.Arrays;

public class ObjectInputStreamDemo02 {

    public static void main(String[] args) {

        // 读取D盘中Java2408目录下student.txt文件中的对象信息

        // 创建ObjectInputStream类对象
        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            inputStream = new FileInputStream("D:/Java2408/Object/students.txt");
            objectInputStream = new ObjectInputStream(inputStream);

            // 通过objectInputStream对象调用方法从指定文件中读取对象信息
            Object object = objectInputStream.readObject();
            // 将object对象转换为其真实类型Student类型的数组
            Student[] students = (Student[]) object;
            // 遍历数组students
            System.out.println(Arrays.toString(students));
            // [Student{name='张三', age=22, gender=男}, Student{name='李四', age=25, gender=男}, Student{name='王五', age=29, gender=男}]

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

5、transient隐藏序列化信息

import java.io.Serializable;

public class Worker implements Serializable {

    private String name;
    // 如果类中某个属性不想被序列化操作,可以使用transient进行修饰
    private transient int age;
    private char gender;

    public Worker() {
    }

    public Worker(String name, int age, char gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Worker{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}
import java.io.*;

public class WorkerObjectOutputStreamDemo01 {

    public static void main(String[] args) {

        // 创建一个Worker类对象
        Worker worker = new Worker("张三", 22, '男');

        // 将worker对象写入到指定文件中
        // 创建ObjectOutputStream类对象
        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            outputStream = new FileOutputStream("D:\\Java2408\\Object\\worker.txt");
            objectOutputStream = new ObjectOutputStream(outputStream);

            // 通过objectOutputStream对象调用方法将worker对象写入到指定文件中
            objectOutputStream.writeObject(worker);
            System.out.println("对象写入完毕");

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
import java.io.*;

public class WorkerObjectInputStreamDemo01 {

    public static void main(String[] args) {

        // 读取F盘中Java2408目录下student.txt文件中的对象信息

        // 创建ObjectInputStream类对象
        InputStream inputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            inputStream = new FileInputStream("D:/Java2408/Object/worker.txt");
            objectInputStream = new ObjectInputStream(inputStream);

            // 通过objectInputStream对象调用方法从指定文件中读取对象信息
            Object object = objectInputStream.readObject();
            // 将object对象转换为其真实类型Worker
            Worker worker = (Worker) object;
            System.out.println(worker); // Worker{name='张三', age=0, gender=男}

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
  • 37
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值