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)
查了文档:当输入过程中意外到达文件或流的末尾时,抛出此异常。
怎么就意外到达文件末尾,这程序好像没什么意外?能处理吗?怎么处理? 作者: 付玉光 时间: 2013-3-11 13:36 本帖最后由 冯海霞 于 2013-3-11 15:16 编辑
class ObjectOutputStreamDemo {
public static void main(String[] args) throws IOException, Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("a.txt"));
//把多个对象,存到对象数组中。
Person[] p = {
new Person("张三", 20, "男"),
new Person("王二", 20, "男"),
new Person("李四", 24, "女")
};