readObject()读取到文件最后会有java.io.EOFException异常(读取不到对象),进行try{}catch(){}捕捉即可
定义一个学生类
package io;
import java.io.Serializable;
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
public Student() {
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
写测试方法
package io;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 向文件中写入多个对象并读取出来
*/
public class TestObjectStream {
public static void main(String[] args) throws Exception{
//向文件中写入对象
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("student.txt"));
Student s1=new Student(1,"张三");
Student s2=new Student(2,"李四");
Student s3=new Student(3,"王五");
Student s4=new Student(4,"赵六");
oos.writeObject(s1);
oos.writeObject(s2);
oos.writeObject(s3);
oos.writeObject(s4);
oos.close();
//读取对象
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("student.txt"));
while(true){
try {
Student stu = (Student) ois.readObject();
System.out.println(stu);
} catch (EOFException e) {
System.out.println("读取完毕");
break;
}
}
ois.close();
}
}
运行结果
Student [id=1, name=张三]
Student [id=2, name=李四]
Student [id=3, name=王五]
Student [id=4, name=赵六]
读取完毕
生成了一个文件

网友评论