java中如何遍历反序列化流中的全部对象?

Hairui瑞 Hairui瑞 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
想问问大神们应该怎么遍历反序列化流中的所有对象

首先通过序列化流向文件中存储了多个对象(这个代码执行了好几次添加的多个对象,确认对象都已经添加进文件中
)
    private void addStudent() throws IOException {//添加学生信息
Person person = new Person();//创建学生类对象
FileOutputStream fos = new FileOutputStream("whr\\src\\dormitory\\学生信息.txt",true);

System.out.println("请按 姓名 学号 年龄 性别 的格式输入学生信息:");
person.setName(sc.next());//将输入的姓名存到对象中
person.setStudentId(sc.nextInt());//将输入的学号存入到对象中
person.setAge(sc.nextInt());//将输入的年龄存入到对象中
person.setSex(sc.next());//将输入的性别存入到对象中
person.setRoom(-1);//先都分配0号宿舍
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(person);//将对象存入文件中
oos.close();
}


然后现在想遍历文件中的所有对象,确抛出了
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
异常,如图:只出现了一个对象:


我使用的遍历代码是这个:
public class test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("whr\\src\\dormitory\\学生信息.txt");
// FileOutputStream fos = new FileOutputStream("whr\\src\\dormitory\\学生信息.txt");
ObjectInputStream ois = new ObjectInputStream(fis);

Person person = (Person)ois.readObject();//遍历反序列化中的所有对象
while (person != null){
System.out.println(person.getName()+person.getStudentId()+person.getSex()+person.getRoom());
person = (Person)ois.readObject();
}

ois.close();
}
}


想问问大神们应该怎么遍历反序列化流中的所有对象
...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
Hairui瑞
Java 51,407 成员 86,130 内容