在 Java 中从文件中反序列化对象
我有一个文件,其中包含 XYZ 类的多个序列化对象。序列化时,每个 XYZ 对象都被附加到文件中。
现在我需要从文件中读取每个对象,并且我只能读取第一个对象。
知道如何从文件中读取每个对象并最终将其存储到列表中吗?
I have a file which contains multiple serialized objects of class XYZ. While serializing, the each XYZ object was appended to the file.
Now I need to read each object from the file, and I am able to read only the first object.
Any idea how I can read each object from the file and eventually store it into a List?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试以下操作:
根据 Tom 的精彩评论,多个
ObjectOutputStream
的解决方案是,Try the following:
Following up on Tom's brilliant comment, the solution for multiple
ObjectOutputStream
s would be,您无法将 ObjectOutputStreams 附加到文件中。它们包含标题以及您编写的对象。修改你的技术。
另外你的 EOF 检测是错误的。您应该单独捕获 EOFException。 OptionalDataException 意味着完全不同的东西。
You can't append ObjectOutputStreams to a file. They contain headers as well as the objects you wrote. Revise your technique.
Also your EOF detection is wrong. You should catch EOFException separately. OptionalDataException means something different entirely.
这对我有用
this works for me
您可以按照下面提到的代码以不同的方式处理文件结尾:
它将从文件中写入和读取多个整数对象,而不会引发任何异常。
You can follow the below mentioned code for handling end of file differently:
It will write and read multiple integer objects from the file without throwing any exception.