- 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;
- }
- }
复制代码 应该写入循环结束标记! |