单个文件中多个java对象的序列化和反序列化
我有一个场景,我有多个 HashMap 对象需要存储在同一个文本文件中。 例如:
a.put("01jan", 13);
a.put("02feb", 13);
a.put("03march", 13);
a.put("04apr", 13);
a.put("05may", 13);
b.put("06june", 12);
b.put("07july", 12);
b.put("08aug", 12);
b.put("09sept", 12);
b.put("10oct", 12);
我想使用java序列化将对象保存在同一个txt文件中。 在我尝试使用 FileOutputStream( file_name,true) 后,有什么方法可以做到这一点吗?另外,当我尝试检索对象时,现在说 HashMap b
,并在需要时说 HashMap a
。有什么方法可以实现这一点吗? 如何检索无序
对象并检索正确的对象?
谢谢, 巴维亚
I have a scenario where I have multiple HashMap objects which need to be stored in the same text file.
for example :
a.put("01jan", 13);
a.put("02feb", 13);
a.put("03march", 13);
a.put("04apr", 13);
a.put("05may", 13);
b.put("06june", 12);
b.put("07july", 12);
b.put("08aug", 12);
b.put("09sept", 12);
b.put("10oct", 12);
I would like to use java serialization to save the objects in the same txt file.
Is there any way to do this one after the other I have tried using the FileOutputStream( file_name,true)
. Also when I try to retrieve objects say HashMap b
now and HashMap a
when the need arises. Is there any way of achieving this?
How do I retrieve out of order
objects and retrieve the correct object?
Thanks,
Bhavya
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将所有 hashmap 对象放入 ArrayList 中,然后序列化 ArrayList 对象。稍后,当您反序列化 ArrayList 对象时,您可以取回各个 HashMap 对象:
You can put all the hashmap objects in an ArrayList and then serialize the ArrayList object. Later on when you deserealize the ArrayList object, you can get individual HashMap objects back:
如果您有许多地图要存储,地图使用键/值对,因此我建议以键/值格式存储数据。 JSON 是基于键/值的人类可读数据可互换格式。它可以存储在文件中,您可以使用 JSONObject(javadoc) 或 GSON 用于序列化/反序列化数据。
例子:
If you have a many maps to store, maps uses key/value pair so I would suggest storing the data in key/value format. JSON is human-readable data interchangeable format which is key/value based. It can be stored in a file and you can use JSONObject(javadoc) or GSON to serialize/unserialize data.
Example:
无序检索对象没有任何优点,只需将所有数据保存到磁盘,并在需要时从磁盘加载所有数据。除非文件至少为 64KB,否则没关系。
如果您的数据较大,您可以将
a
和b
放在单独的文件中,但它不太可能产生超过几毫秒的差异,但会使您的代码更加复杂。您无法将 ObjectOutputStream 附加到文件。当你读回数据时,你只会得到第一个。 (检索数据可能会很痛苦,但最好不要尝试)
There is no advantage is retrieving objects out of order, just save all the data to disk and when you need them load all the data from disk. Unless the file is at least 64KB it won't matter.
If your data is larger, you could place
a
andb
in separate files but its unlikely to make more than a few milli-seconds difference but will make your code more complex.You cannot append ObjectOutputStream's to a file. When you read the data back, you will only ever get the first. (You can retrieve the data with a lot of pain, but its best not to try)
另一种方法是将每个
HashMap
作为 Zip 存档中的一个条目。Another approach is to put each
HashMap
as an entry in a Zip archive.