public static void main(String[] args) throws IOException,ClassNotFoundException
{
writeObj();//将对象写入到person.txt文件中。
readObj();//将person.txt文件中的对象打印到控制台上。
}
public static void readObj() throws IOException,ClassNotFoundException
{
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.txt"));
Object obj = null;
while ((obj=ois.readObject())!=null )
{
if (!(obj instanceof Person))
{
throw new RuntimeException ("对象错误");
}
Person p = (Person) obj;
System.out.println(p);
}
ois.close();
}
public static void writeObj() throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.txt"));
oos.writeObject(new Person("lisi","39"));
oos.writeObject(new Person("wangwu","40"));
oos.writeObject(new Person("sunliu","50"));
oos.flush();
oos.close();
}
}
复制代码
运行结果是正确的,但会报出以下异常:
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputSt
ream.java:2601)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at ObjStreamDemo.readObj(ObjStreamDemo.java:58)
at ObjStreamDemo.main(ObjStreamDemo.java:51)