本帖最后由 谢冬 于 2013-3-11 04:19 编辑
- package com.itheima_01;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class ObjectOutputStreamDemo {
- public static void main(String[] args) throws IOException, Exception {
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
- oos.writeObject(new Person("张三", 20, "男"));
- oos.writeObject(new Person("王二", 20, "男"));
- oos.writeObject(new Person("李四", 24, "女"));
- oos.flush();
- oos.close();
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream("a.txt"));
- Person p = null;
- while((p = (Person)ois.readObject()) != null)
- {
- System.out.println(p);
- }
- ois.close();
- }
- }
复制代码- package com.itheima_01;
- import java.io.Serializable;
- public class Person implements Serializable{
- private static final long serialVersionUID = 613659699548582156L;
- private String name;
- private int age;
- private String sex;
- public Person(String name, int age, String sex) {
- super();
- this.name = name;
- this.age = age;
- this.sex = sex;
- }
- @Override
- public String toString() {
- return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
- }
- }
复制代码 控制台的提示信息:
Person [name=张三, age=20, sex=男]
Person [name=王二, age=20, sex=男]
Person [name=李四, age=24, sex=女]
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2571)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at com.itheima_01.ObjectOutputStreamDemo.main(ObjectOutputStreamDemo.java:22)
查了文档:当输入过程中意外到达文件或流的末尾时,抛出此异常。
怎么就意外到达文件末尾,这程序好像没什么意外?能处理吗?怎么处理?
|