2013-03-05 51 views
0

無論如何檢查類ObjectInputStream的方法readObject是否已完成讀取文件,而不是捕獲其拋出的異常?ReadObject方法

如果否。我怎麼能make outNemamast.writeObject(accountRecord);在這種情況下達成的聲明?

// read oldmast.ser 
    try { 
     while (true) { 
      accountRecord = (AccountRecord) inOldmast.readObject(); 
      //read trans.ser 
      while (true) { 
       transactionRecord = (TransactionRecord) inTrans.readObject(); 
       if (transactionRecord.getAccountNumber() == accountRecord.getAccount()) { 
        accountRecord.combine(transactionRecord); 
       }//end if 
      }//end inner while 
      outNewmast.writeObject(accountRecord); 
     }//end while 
    }//end try 
    catch (ClassNotFoundException e) { 
     System.err.println("Error reading file."); 
     System.exit(1); 
    }//end catch   
    catch (IOException e) { 
     System.err.println("Error reading file."); 
     System.exit(1); 
    }//end catch 

回答

2

最好的辦法是事先序列化元素的數量,所以你可以只做:

cnt = file.readInt(); 
for (int i=0;i<cnt;i++) { 
    file.readObject(); 
} 

@ChrisCooper提出的方法是不reli正如文件中所述。有些流不執行它,或返回近似結果(理論上,它仍然可以在還有一些數據時返回0,例如 - 網絡流)。

因此,在看同一文檔中,我們發現該特定塊:

任何試圖讀取超過由相應writeObject方法寫入的 自定義數據的邊界的對象數據將導致 一個OptionalDataException到被拋出的eof字段值爲true。 超出分配數據末尾的非對象讀取將以 反映數據結束的方式與它們將指示流末尾的方式相同:字節讀取將返回-1作爲字節讀取或 字節數讀取和原始讀取將拋出EOFException。如果 沒有相應的writeObject方法,則默認的 序列化數據結束標記分配數據的結束。

所以,最好的辦法是將捕獲一個OptionalDataException並檢查它的eof領域true

而且,以進一步消化了答案,這就是你想要的方式:

TransactionRecord readRecord(ObjectInputStream stream) throws OptionalDataException, IOException { 
    try { 
     transactionRecord = (TransactionRecord) stream.readObject(); 
    } catch (OptionalDataException e) { 
     if (e.eof) { 
      return null; 
     } else { 
      throw e; 
     } 
    } 
    return transactionRecord; 
} 
..... 
TransactionRecord record; 
while ((record = readRecord(inTrans)) != null) { 
    doSomethingWithRecord(record); 
} 
endOfFile(); 
相關問題