已编辑 因此,我尝试将 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
并且我不确定为什么,因为我有一个条件不访问/保存 elem,除非 ((p = (Product) in .readObject()) != null)
。我不知道如何避免 EOF。我尝试使用 read()
检查,但它只会避免问题,而不会帮助我保存更改。另外,我注意到只保存了我提交的最后一个元素。
有什么建议么?
编辑
实现建议后,我的错误切换为 java.io.StreamCorruptedException: invalid type code: AC
。
我读了这个https://stackoverflow.com/a/2395269/4180889但我不清楚如果我想保留内容应该做什么。
最佳答案
I noticed only the last element I submit is saved.
这是因为写操作是在截断模式下完成的。
fileOut = new FileOutputStream("products.ser");
使用 true
标志进行追加模式:
fileOut = new FileOutputStream("products.ser", true);
参见more
关于Java 可序列化 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29622705/