when I enter the inputs as objects, they can be easily saved and able to read in the serialization process but when I add them a second time, objects which are added second time saved in the file, but unable to read them .showing an error related to an invalid type code AC.
try (FileOutputStream file = new FileOutputStream(filename,true);
ObjectOutputStream out = new ObjectOutputStream(file))
{
for (Product pro : productList) {
out.writeObject(pro);
System.out.println(pro);
}
System.out.println("Object has been saved successfully");
productList.clear();
} catch (IOException ex) {
System.out.println("IOException is caught");
ex.printStackTrace();
}
}
Read file code:
try (FileInputStream file = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file))
{
while ( (p1 = (Product) in.readObject()) != null)
{
newProductList.add(p1);
System.out.println(p1);
System.out.println("done");
System.out.println(newProductList.size());
}
in.close();
file.close();
System.out.println("Reached end of file.");
} catch (IOException ex) {
System.err.println("Error while reading product data: " + ex.getMessage());
}
catch (ClassNotFoundException e) {
System.err.println("Class not found during deserialization: " + e.getMessage());
}
return newProductList;
}
Please help me fix this error.
I need a correct code to fix my problem