摘自http://blog.csdn.net/fjdingsd/article/details/46765803
使用ObjectInputStream的readObject()方法如何判斷讀取到多個對象的結尾
import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import cn.com.mybolg.bean.Person; /* * 若文件中有若干個Object對象,你用ObjectInputStream中的readObject()去讀,何時判讀到結尾? * 方法之一:(常用的方法)將若干個對象(數量不定)都裝入一個容器中(如:ArrayList之類), * 然后將容器這一個對象寫入就行了。讀取時,只要讀取一個對象(即容器對象)就行了。 * * 方法之二:(若不想用容器),則由於數量不定,正是用EOFException來判斷結束。 * 代碼結構如下:(無論是readInt()讀int,還是readObject()讀對象) * try{ * while(true) { * Object o=ois.radObject(); * 處理已讀出的對象o; * } * } * catch(EOFException e){ * //已從流中讀完。 * } * finallly { * 流的關閉。 } */ public class ObjectInputStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream("F:\\person.object"); ObjectInputStream osi = new ObjectInputStream(fis); try { while(true) { Person p = (Person) osi.readObject(); System.out.println(p.getName()+":"+p.getAge()); } } catch(EOFException e) { } finally { osi.close(); } } }
以下是自己的試驗:
往文件里存多個對象也沒問題,調用writeObject()一直往里寫即可,readObject()一次返回一個對象,再readObject()一次返回第二個對象,自動在每個對象后面做標記。並且同一個文件中可以依次存入不同類的對象。先存入一個Person對象,再存入一個Demo對象,再存個Haha對象都可以。按順序讀就行了。
package packa; import java.io.*; class ObjectInputOutputStream { public static void main(String[] args)throws Exception { writeObj(); readObj(); } private static void writeObj()throws Exception { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.object")); oos.writeObject(new Person("liu", 30, "kr")); oos.writeObject(new Person2("liu", "kr", "kr2")); oos.writeObject(new Person3(10, 30, 50)); oos.close(); } private static void readObj()throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.object")); System.out.println(ois.readObject()); System.out.println(ois.readObject()); System.out.println(ois.readObject()); ois.close(); } }
package packa; import java.io.*; class Person implements Serializable { public static final long serialVersionUID = 44L; String name; transient int age; static String country = "cn"; Person(String name, int age, String country) { this.name = name; this.age = age; this.country = country; } public String toString() { return name + " " + age + " " + country; } } class Person2 implements Serializable { public static final long serialVersionUID = 45L; String name; String country; String country2; Person2(String name, String country, String country2) { this.name = name; this.country = country; this.country2 = country2; } public String toString() { return name + " " + country + " " + country2; } } class Person3 implements Serializable { public static final long serialVersionUID = 46L; int age; int age2; int age3; Person3(int age, int age2, int age3) { this.age = age; this.age2 = age2; this.age3 = age3; } public String toString() { return age + " " + age2 + " " + age3; } }