将许多java对象写入单个文件 [英] writing many java objects to a single file

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

问题描述

如何将多个可序列化对象写入单个文件,然后在需要时读取一些对象?

how can I write many serializable objects to a single file and then read a few of the objects as and when needed?

推荐答案

您必须自己实现索引方面,否则可以这样做。当你序列化一个对象时,你基本上会得到一个 OutputStream ,你可以指向你想要的任何地方。以这种方式将多个对象存储到文件中会很简单。

You'd have to implement the indexing aspect yourself, but otherwise this could be done. When you serialize an object you essentially get back an OutputStream, which you can point to wherever you want. Storing multiple objects into a file this way would be straightforward.

当你想要读回几个对象时,很难实现。您如何知道如何在包含您想要的特定对象的文件中寻找位置?如果你总是按照你编写它们的顺序读取对象,那么从文件开头开始,这不会有问题。但是如果你想随机访问流的中间中的对象,你将不得不想出一些方法来确定你感兴趣的特定对象的字节偏移量。

The tough part comes when you want to read "a few" objects back. How are you going to know how to seek to the position in the file that contains the specific object you want? If you're always reading objects back in the same order you wrote them, from the start of the file onwards, this will not be a problem. But if you want to have random access to objects in the "middle" of the stream, you're going to have to come up with some way to determine the byte offset of the specific object you're interested in.

(这种方法与同步甚至Java本身无关;你必须设计一个符合你的要求和环境的方案。)

(This method would have nothing to do with synchronization or even Java per se; you've got to design a scheme that will fit with your requirements and environment.)

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

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