topic
Complete the operation of accessing objects from the file.txt file through serialization and deserialization streams
analysis
When using deserialization to read objects, he can only read the first object. If you want to read multiple objects, you need to use a loop to read the data
. The available () method in FileInputStream can return the remaining files. The number of bytes, this method can be used as a loop termination condition. The
student class should also implement the Serializable interface in order to serialize successfully
code
学生类
package com.company.test;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 42L;
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
序列化和反序列化
package com.company.test;
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.txt"));
//分开写,后面要用到,来做循环终止条件
FileInputStream fileInputStream = new FileInputStream("file.txt");
ObjectInputStream in = new ObjectInputStream(fileInputStream);
Student s1 = new Student("张三", 22);
Student s2 = new Student("李四", 23);
Student s3 = new Student("王五", 24);
out.writeObject(s1);
out.writeObject(s2);
out.writeObject(s3);
//使用反序列化流利用循环来打印文件中的内容
while (fileInputStream.available() > 0){//代表文件中还有内容
Object obj = in.readObject();
Student s = (Student) obj;
System.out.println(s);
}
in.close();
out.close();
}
}