开发者社区> 问答> 正文

java中用readObject方法遍历时报EOFException

public class SequenceDemo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
    File s=new File("d:/Mydoc/123.txt");
    Students zhan=new Students("张三",21,true);
    Students li=new Students("李三",22,true);
    Students liu=new Students("刘三",20,true); 
    ObjectOutputStream dos=new ObjectOutputStream(new FileOutputStream(s));
    dos.writeObject(zhan);
    dos.writeObject(li);
    dos.writeObject(liu);
    System.out.println("序列化完成");
    dos.flush();
    dos.close();
    ObjectInputStream fos=new ObjectInputStream(new FileInputStream(s));
    Students m=null;
    try{
        while((m=(Students)fos.readObject())!=null){
        System.out.println("名字:"+m.getName()+
                "\t年龄:"+m.getAge()+"\t性别:"+
                (m.isGender()?"男":"女"));    
    }
    }catch(EOFException e){
        System.out.println("输出结束");
    }
    fos.close();
}
}

运行结果:
screenshot

展开
收起
蛮大人123 2016-03-19 11:09:25 2958 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    dos.writeObject(liu);后加个dos.writeObject(null);能解决。

    2019-07-17 19:07:44
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载