I have a file by the name "admin_product.bin". I want to append objects to the file. After searching I found a class as follows:
public class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) throws IOException {
super(out);
}
@Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}
}
The above code helped we append data to my file. However when I try to read the file using ObjectInputStream
, it throws an error as follows:
java.io.StreamCorruptedException: invalid stream header: 79737200
My code sample is:
public static void write_into_file() throws IOException {
File file = null;
file = new File("admin_product.bin");
if(!file.exists()) {
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(new FileOutputStream(file));
os.writeObject(prd);
System.out.println("Done!");
} catch(Exception e) {
System.out.println("Exception = " + e);
} finally {
if(os != null) {
os.close();
}
}
}
else {
AppendingObjectOutputStream as = null;
try {
as = new AppendingObjectOutputStream(new FileOutputStream(file));
as.writeObject(prd);
System.out.println("Done!");
} catch(Exception e) {
System.out.println("Exception = " + e);
} finally {
if(as != null) {
as.close();
}
}
}
}
Can anyone please tell me where I am going wrong?
I have the answers from the following questions (yet couldn't figure out the problem) -