简体   繁体   English

如何将多个对象写入文件?

[英]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. 我目前正在以FileOutputStream("filename", true)以便它将对象附加到文件的末尾,而不是覆盖它。 But I get this error : 但是我得到这个错误:

java.io.StreamCorruptedException: invalid type code: AC java.io.StreamCorruptedException:无效的类型代码: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 . 当您想编写一条消息时,首先将其序列化为ByteArrayOutputStream Then open the file for appending with DataOutputStream - write the length with writeInt , then write the data. 然后打开要与DataOutputStream追加的文件-使用writeInt长度,然后写入数据。

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. 从流中读取数据时,可以使用DataInputStream将其打开,然后重复调用readInt来查找下一条消息的长度,然后再次调用readFully来读取消息本身。 Put the message into ByteArrayInputStream and then deserialize from that. 将消息放入ByteArrayInputStream ,然后从中反序列化。

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. 或者,使用比内置Java序列化更好的序列化格式-我是协议缓冲区的支持者,但有很多可用的替代方法。 The built-in serialization is too brittle for my liking. 内置序列化对于我来说太脆弱了。

You can't append different ObjectOutputStreams to the same file. 您不能将不同的ObjectOutputStreams附加到同一文件。 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> . 您需要serialize / deserialize serialize List<T> Take a look at this stackoverflow thread. 看一下这个 stackoverflow线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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