题目
通过序列化流与反序列化流完成从file.txt文件存取对象的操作
分析
在使用反序列化读取对象的时候,他只能读取第一个对象,若想要读取多个对象就需要使用循环来进行读取数据
FileInputStream中的available()方法可以返回文件中剩余的字节数,用此方法可以作为循环终止条件
学生类还应该实现 Serializable 接口,才能序列化成功
程序代码
学生类
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();
}
}