![](/img/trans.png)
[英]How to read multiple objects from a text file and then send to an ArrayList?
[英]How to read multiple same objects from a file
我正在嘗試使用 Serializable 從文件(類的相同對象)中讀取對象,但是當它讀取所有對象時,它給了我錯誤IOException
, java.io.ObjectInputStream$BlockDataInputStream.peekByte
。
我正在閱讀對象,然后保存到列表。 但是當它到達時,可以說 EOF 它會引發錯誤。
這是我的方法:
private static void updateBook(String name) {
// TODO Auto-generated method stub
FileInputStream fis = null;
ObjectInputStream in = null;
Object obj = new Object();
List<Object> libb = new ArrayList<Object>();
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} finally {
in.close();
//fis.close();
}
for(int j = 0; j < libb.size(); ++j) {
Book li = new Book();
li = (Book) libb.get(j);
System.out.println(li.getBookName());
}
//
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not Exist!");
}
}
誰能告訴我如何從while(true)
避免這個錯誤。
完全錯誤:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
在您的try
語句中,您缺少EOFException
的 catch 子句:
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
// treat it as you like
} finally {
in.close();
//fis.close();
}
你應該添加:
catch (EOFException e){
// do stuffs
}
因為EOFException
沒有被捕獲。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.