黑马程序员技术交流社区

标题: ObjectInputStream类读取 [打印本页]

作者: 李靖    时间: 2012-10-29 12:46
标题: ObjectInputStream类读取
本帖最后由 bhxiaobo 于 2012-10-29 15:04 编辑

如果通过ObjectOutputStream往磁盘文件写入若干个对象,如何通过ObjectInputStream读到所有的对象呢,通过while循环
public static void main(String[] args) throws Exception {
  Person person=new Person("wangwu",13);
  Person person1=new Person("zhangsan",13);
  ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("demo.txt"));
  objectOutputStream.writeObject(person);
  objectOutputStream.writeObject(person1);
  objectOutputStream.flush();
  objectOutputStream.close();
  ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("demo.txt"));
  Object object;
  while((object=objectInputStream.readObject()) !=null){
   System.out.println(((Person)object).getName());
  }
}
下面代码会报
Exception in thread "main" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at com.io.lijing.ObjectStream.main(ObjectStream.java:22)
作者: 张忠豹    时间: 2012-10-29 13:18
  1. package java1.io;

  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.io.Serializable;

  7. public class ObjectStreamTest {

  8. /**
  9. * @param args
  10. */
  11. public static void main(String[] args) throws Exception {
  12. Person person=new Person("wangwu",13);
  13. Person person1=new Person("zhangsan",13);
  14. ObjectOutputStream objectOutputStream=new ObjectOutputStream(new FileOutputStream("demo.txt"));
  15. objectOutputStream.writeObject(person);
  16. objectOutputStream.writeObject(person1);
  17. //应该写入循环结束标记
  18. objectOutputStream.writeObject(null);
  19. objectOutputStream.flush();
  20. objectOutputStream.close();
  21. ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("demo.txt"));
  22. Object object =null;
  23. while((object=objectInputStream.readObject()) !=null){
  24. System.out.println(object);
  25. System.out.println(((Person)object).getName());
  26. }
  27. }


  28. }
  29. class Person implements Serializable{
  30. private String name;
  31. private int age;

  32. public Person(String name,int age){
  33. this.name = name;
  34. this.age = age;
  35. }

  36. public String getName() {
  37. return name;
  38. }
  39. }
复制代码
应该写入循环结束标记!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2