ObjectInputStream無論是讀對象,還是記取int等java的基本數據類型,在判結束時,絕對既不是-1,也不是什么null。
若文件中有若干個int的數,你用DataInputStream中的readint()去讀,何時判讀到結尾?絕對既不是-1,也不是什么null
同樣道理:若文件中有若於個Object對象,你用ObjectInputStream中的readObject()去讀,何時判讀到結尾?絕對既不是-1,也不是什么null
方法之一:(常用的方法)將若干個對象(數量不定)都裝入一個容器中(如:ArrayList之類),然后將容器這一個對象寫入就行了。讀取時,只要讀取一個對象(即容器對象)就行了
例如:
1 public ArrayList<Person> readPerson(String pathName){ 2 ArrayList<Person> list = null; 3 FileInputStream fis; 4 ObjectInputStream ois; 5 try { 6 fis = new FileInputStream(pathName); 7 ois = new ObjectInputStream(fis); 8
9 list = (ArrayList<Person>) ois.readObject(); 10
11 System.out.println("加載人員庫完成!"); 12 fis.close(); 13 ois.close(); 14 } catch (FileNotFoundException e) { 15 e.printStackTrace(); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } catch (ClassNotFoundException e) { 19 e.printStackTrace(); 20 }finally{ 21 return list; 22 } 23 }
用ArrayList來包裹Person,直接讀入一個ArrayList對象。
方法之二:使用EOFException來判斷結束。
try{
while(true)
{
Object o=ois.radObject();
//處理已讀出的對象o;
}
}catch(EOFxception e){
//已從流中讀完。
}
finallly{
流的關閉。
}