//读取序列化的对象,怎么判断是否到达末尾
import java.io.*;
class SerialDemo
{
public static void main(String[] args) throws Exception
{
//write();
read();
}
public static void read() throws Exception
{
ObjectInputStream obji = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p =null;
while((p=(Person)obji.readObject()) != null)// !!!到达末尾,再读取会发生java.io.EOFException异常
{
System.out.println(p);//
}
obji.close();
}
public static void write() throws IOException
{
ObjectOutputStream objo = new ObjectOutputStream(new FileOutputStream("obj.txt"));
objo.writeObject(new Person("zhang", 23));
objo.writeObject(new Person("li", 20));
objo.writeObject(new Person("wang", 21));
//objo.writeObject(null); 网上有人这样建议!!!
objo.close();
}
}
class Person implements Serializable
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String toString()
{
return "name: "+name+" age: "+age;
}
}
//while((p=(Person)obji.readObject()) != null) 不能判断是否到达末尾,网上建议在写入一个空的Object,即objo.writeObject(null),
这样的话,通过(p=(Person)obji.readObject()) != null 可以检测到达末尾,但是感觉这不是解决的办法,,各位有什么好的建议,,,谢谢!!!
|