Reputation: 719
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
Upvotes: 1
Views: 4230
Reputation: 533780
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
and b
in separate files but its unlikely to make more than a few milli-seconds difference but will make your code more complex.
FileOutputStream( file_name,true)
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)
Upvotes: 1
Reputation: 168845
Another approach is to put each HashMap
as an entry in a Zip archive.
Upvotes: 0
Reputation: 89189
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:
{"hashmap1":
[
{"01jan": 13},
{"02feb": 13},
{"03march", 13}
]
}
Upvotes: 2
Reputation: 2540
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:
List<HashMap> list = new ArrayList<HashMap>();
list.add(a);
list.add(b);
// serialize the list object
Upvotes: 7