comatose
comatose

Reputation: 1962

How to write multiple objects to file?

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,

Upvotes: 1

Views: 4428

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1501043

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.

Upvotes: 3

KV Prajapati
KV Prajapati

Reputation: 94645

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

Upvotes: 2

user207421
user207421

Reputation: 310957

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.

Upvotes: 2

Related Questions