如何写入多个对象到文件? [英] How to write multiple objects to file?

查看:131
本文介绍了如何写入多个对象到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个对象写入一个文件,但问题是我没有立即写入所有的对象。我必须写一个对象,然后关闭文件,然后也许过了一段时间,我想添加另一个对象到同一个文件。

我目前正在做
FileOutputStream(filename,true)
,这样它会将对象附加到文件的末尾,而不会覆盖它。但我得到这个错误:


java.io.StreamCorruptedException:无效的类型代码:AC




任何想法如何解决这个问题?



谢谢,

解决方案

不能将不同的ObjectOutputStreams追加到同一个文件中。您将不得不使用不同的序列化形式,或者读取文件并将所有对象和新对象写入新文件。


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,

解决方案

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.

这篇关于如何写入多个对象到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆