1

I want to write multiple objects to a file, but the problem is that I dont have all the objects to write at once. I have to write one object and then close the file, and then maybe after sometime I want to add another object to the same file.

I am currently doing it as FileOutputStream("filename", true) so that it will append the object to the end of file and not overwrite it. But I get this error :

java.io.StreamCorruptedException: invalid type code: AC

any ideas how can I solve this issue ?

Thanks,

comatose
  • 1,952
  • 7
  • 26
  • 42
  • if you do not need random access to the objects, @Jon's answer is on the mark. However if you do (i.e. dont want to read all of them), you need directory at the beginning (or end) of the file w/ some the offset, some key to and length. Alternatively just use separate files, nowadays file systems (esp ext4) are pretty good at organizing even small files efficiently (esp if you have SSD :D ) – bestsss Oct 20 '11 at 06:19
  • Thank you everyone, The solution proposed by Jon seems robust but its too complicated for me, so I guess I'll settle for your solution (creating separate files for each new object) or EJP's solution of reading old objects and then write all the old+new objects to the file gain. – comatose Oct 21 '11 at 01:43

3 Answers3

3

One option is to segment the file into individual messages. When you want to write a message, first serialize it to a ByteArrayOutputStream. Then open the file for appending with DataOutputStream - write the length with writeInt, then write the data.

When you're reading from the stream, you'd open it with DataInputStream, then repeatedly call readInt to find the length of the next message, then readFully to read the message itself. Put the message into ByteArrayInputStream and then deserialize from that.

Alternatively, use a nicer serialization format than the built-in Java serialization - I'm a fan of Protocol Buffers but there are lots of alternatives available. The built-in serialization is too brittle for my liking.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

You can't append different ObjectOutputStreams to the same file. You would have to use a different form of serialization, or read the file in and write out all the objects plus the new objects to a new file.

user207421
  • 305,947
  • 44
  • 307
  • 483
2

You need to serialize/deserialize the List<T>. Take a look at this stackoverflow thread.

Community
  • 1
  • 1
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186