0

I am obliged to open a ObjectOutputStream, then write an object an finally close the stream. I do that multiple times using the following code :

 // try-with-statement is very practical 
 try(FileOutputStream fos = new FileOutputStream("G.txt") ;
    ObjectOutputStream oos = new ObjectOutputStream(fos);){

    oos.writeObject(v);

} catch (IOException e) {
    e.printStackTrace();
}

But what I want is to append the objects serialized in the "G.txt" ? how to do that please ? I can't figure that out ?

2 Answers2

0

You could use FileOutputStream(String name, boolean append) constructor.

barunsthakur
  • 1,196
  • 1
  • 7
  • 18
  • No it isn't. That will suffice to append the data, but it will throw a [`StreamCorruptedException: invalid type code AC`](http://stackoverflow.com/a/2395269/207421) on reading, when you get to the join. – user207421 Jun 21 '15 at 10:06
  • it is not adviced to OpenClose multiple times the OOS or OIS ? –  Jun 21 '15 at 10:17
  • 1
    @OSryx It doesn't work. Follow the link and see why. It is possible to overcome this issue but it's best not to provoke it in the first place. – user207421 Jun 21 '15 at 10:21
  • If you want to append to the file, You can subclass ObjectOutputStream and override `writeStreamHeader` method to do a `reset()`. Then select the ObjectOutputStream bansed on use cases(when appending, use the subclasses OOS ans when not appending use the OOS). – barunsthakur Jun 21 '15 at 10:39
0

You can put the FileOutputStream into append mode for the second and subsequent writes, but you must also use an AppendingObjectOutputStream for the second and subsequent writes. You will find this class all over the Internet. It overrides writeStreamHeader() to do nothing. Otherwise you will get a StreamCorruptedException: invalid type code AC on reading, when you get to the join.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483