简体   繁体   中英

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,

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM