[英]Java Serializable EOF
已編輯,因此我嘗試將.Product類型的對象保存在.ser文件中,其中包含以下名稱:每次添加新產品時,我都會將其添加到文件中。 然后,每次啟動窗口時,我想通過在窗口的構造函數中調用以下方法來讀取以前保存在TreeSet中的這些產品:
public void updateCurrentProducts()
{
Product p=null;
System.out.println("Updating the tree of products.");
try
{
FileInputStream fileIn = new FileInputStream("products.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
int c;
// if((c=in.read()) != -1)
{
// System.out.println("Not eof yet.");
while ((p = (Product) in.readObject()) != null)
{
addProduct(p);
System.out.println("Just found "+p.name+".");
}
}
in.close();
fileIn.close();
}catch(IOException ix)
{
ix.printStackTrace();
return;
} catch (ClassNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
這是我添加產品的方式:
public void addProduct(Product p)
{
System.out.println("Succesfully added new peoduct.");
FileOutputStream fileOut;
try
{
fileOut = new FileOutputStream("products.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(p);
System.out.println("Just saved "+p.name);
productTree.add(p);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in products.ser");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但是我得到java.io.EOFException
,我不確定為什么,因為我有一個條件,除非((p = (Product) in.readObject()) != null)
否則我不能訪問/保存一個elem。 我不確定如何避免EOF。 我嘗試使用read()
檢查,但是這樣做只會避免問題,無法幫助我保存更改。 另外,我注意到僅保存了我提交的最后一個元素。 有什么建議么?
編輯實施建議后,我的錯誤切換到java.io.StreamCorruptedException: invalid type code: AC
。
我讀到了這個https://stackoverflow.com/a/2395269/4180889,但是對於我來說,如果要保留內容我該怎么辦還不清楚。
我注意到只有我提交的最后一個元素被保存。
這是因為寫操作是在截斷模式下完成的。
fileOut = new FileOutputStream("products.ser");
對附加模式使用true
標志:
fileOut = new FileOutputStream("products.ser", true);
查看更多
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.