I need to append multiple objects in a single file in multiple sessions.
I searched for a fair amount of time and I got two solutions from here.
1) Using List to get already written objects from the file, add new objects to the List and rewriting the file.
2) Overriding writeStreamHeader()
I followed the second method i.e., overriding writeStreamHeader()
.
He stated that
A workaround is to subclass
ObjectOutputStream
and overridewriteStreamHeader()
. The overridingwriteStreamHeader()
should call the super writeStreamHeader
method if it is the first write to the file and it should callObjectOutputStream.reset()
if it is appending to a pre-existing ObjectOutputStream within the file.
So I tried this
class ObjectOutput extends ObjectOutputStream
{
protected ObjectOutput(OutputStream os) throws IOException, SecurityException {
super(os);
}
protected void writeStreamHeader() throws IOException
{
File file = new File("abc.txt");
if(file.exists())
{
reset();
}
else
{
file.createNewFile();
super.writeStreamHeader();
}
}
}
When I try to read the objects from the file there is an exception
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at Get.main(Get.java:11)
Then I tried this solution
Now, it worked perfectly!
So, what's wrong with the first code? I called the super.writeStreamHeader()
when there is no file and the second method also calls the same method in the same scenario.
So,is there anything I am missing?
Thank you.