所以我在一個方法中擁有一個作業的ObjectOutputStream,我通過呼叫main中的方法開始作業。然后我需要讀取它所創建的檔案并列印出其中所有的5個物件。現在我只列印出了第一個物件。
public static AccountSerializableserializReadObject() throws ClassNotFoundException, IOException {
AccountSerializable read = null;
try { //為檔案account.ser創建一個輸入流。
ObjectInputStream input = new ObjectInputStream(new FileInputStream("account. ser"))。)
read = (AccountSerializable) input.readObject();
input.close()。
} catch (IOException i) {
throw i;
}catch(ClassNotFoundException c){
throw c;
}
return read;
}
public static void main(String[] args) {
try {
System.out.println(serializReadObject())。
} catch (ClassNotFoundException | IOException e) {
System.out.println("Class not found")。
e.printStackTrace()。
}
}
我曾嘗試拋出
boolean eof = false;
while(!eof){
try{
//讀取資料。
}catch(EOFException e){
eof = true;
}
}
在serializReadObject中進行回圈,我也嘗試在main中抓取它,但我一直得到一個錯誤提示:"EOFException的抓取塊無法到達,它已經被抓取塊處理了" 然后我試著去掉IOException,只放EOFEception,但可惜的是,它一直強迫我用IOException包圍我的讀取。是否有其他方法可以用EOF來回圈呢?
uj5u.com熱心網友回復:
你只得到了第一個物件,因為你在每次呼叫時都會打開和關閉流。有很多方法可以實作你想要的東西。一種方法是使用List<AccountSerializable>:
public static List<AccountSerializable> serializeReadObjects() throws IOException, ClassNotFoundException{
//為檔案account.ser創建一個輸入流。
//這一行將在出錯時拋出一個IOException。
//我們不需要在這個方法中捕捉它。
ObjectInputStream input = new ObjectInputStream(new FileInputStream("account. ser"))。)
//創建串列以保存讀入的帳戶。
List<AccountSerializable> accounts = new ArrayList<>()。
//繼續讀,直到拋出EOFException。
boolean keepReading = true。
while(keepReading) {
try {
//讀入序列化的帳戶。
AccountSerializable read = (AccountSerializable) input.readObject() 。
//將讀入的序列化賬戶添加到串列中。
accounts.add(read)。
} catch(EOFException eofe) {
//我們在檔案的末端,所以停止閱讀。
keepReading = false;
input.close()。
} catch(IOException ioe) {
//除了EOF之外的輸入流錯誤,不知道該怎么做。
input.close()。
拋出 ioe。
} catch(ClassNotFoundException cnfe) {
//不知道在這種情況下該怎么做,所以關閉輸入。
input.close()。
拋出 cnfe。
}
}
return accounts;
}
public static void main(String[] args) {
List<AccountSerializable> accounts = null;
try {
// get list of read in accounts; try // get list of read in accounts
accounts = serializeReadObjects();
} catch(ClassNotFoundException | IOException e) {
e.printStackTrace()。
}
//迭代已讀賬戶的串列,并將其輸出到stdout。
for(AccountSerializable account : accounts) {
System.out.println(account)。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/320035.html
標籤:
上一篇:try/except和環境管理器
