EDITED So I'm trying to save in a .ser file objects of type Product( containing name, quantity, price ) as it follows: each time I add a new product I add it in the file. Then, each time I launch a window, I want to read these products I previously saved, in a TreeSet by calling the following method in the window's constructor:
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();
}
}
This is how I add products:
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();
}
}
However I get java.io.EOFException
and I'm not sure why, since I have a condition not to access/save an elem unless ((p = (Product) in.readObject()) != null)
. I'm not sure how to avoid EOF. I tried with read()
check, but it would simply avoid the problem, not help me save my changes. Also, I noticed only the last element I submit is saved.
Any suggestions?
EDIT
After implementing the suggestion, my error switched to java.io.StreamCorruptedException: invalid type code: AC
.
I read this https://stackoverflow.com/a/2395269/4180889 but it's not clear for me what I should do if I want to keep the content.