ObjectOutputStream读取文件多个对象时报出EOFException问题

写入Student对象到Student.txt

public class WriterStudent {

    public static void main(String[] args) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Student.txt"));
            Student stu1 = new Student("徐恺",19);
            Student stu2 = new Student("路娟娟",18);
            Student stu3 = new Student("崔亚涛",20);
            oos.writeObject(stu1);
            oos.writeObject(stu2);
            oos.writeObject(stu3);
            //写入结束标志方便读取(非常重要,如果不写入,在读取的时候无法定位读取结束);
            oos.writeObject(null);
            oos.close();
        }catch (IOException e) {

            e.printStackTrace();
        }

    }

}

读取Student对象到console

public class ReaderStudent {

    public static void main(String[] args) {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("Student.txt"));
            try {
                Student s = null;
                while(true){
                    if((s = (Student)ois.readObject()) != null){
                        s.showInfo();

                    }else{
                        break;
                    }
                }
            } catch (ClassNotFoundException e) {

                e.printStackTrace();
            }
            ois.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

}

序列化Student类

package com.lanou3g.job11;

import java.io.Serializable;

public class Student implements Serializable{

    private String name;
    private int age;
    public Student() {
        super();

    }
    public Student(String name, int age) {
        super();
        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;
    }

    public void showInfo(){
        System.out.println("姓名:" + name + ",年龄" + age);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值