黑马程序员技术交流社区
标题:
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
package java1.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectStreamTest {
/**
* @param args
*/
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.writeObject(null);
objectOutputStream.flush();
objectOutputStream.close();
ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream("demo.txt"));
Object object =null;
while((object=objectInputStream.readObject()) !=null){
System.out.println(object);
System.out.println(((Person)object).getName());
}
}
}
class Person implements Serializable{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
}
复制代码
应该写入循环结束标记!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2