Reputation: 2535
So I run into a casting problem with storing HashMap
properties to a Properties
file because the key of the HashMap
is an object that cannot be cast to java.lang.String
because properties must be (String, String)
and my HashMap
is (Object, Long)
.
I just want to save the contents of the HashMap
to a file so I can load those contents back into the HashMap
the next time the program is ran.
I have gone through an excessive amount of worthless attempts to try to refill HashMaps
with objects they contained before they were saved. I tried to think of an easy way to convert the object to a string which I can do, but since Properties
and HashMaps
are not indexed, I can not change those strings back to the object they need to be. How to achieve this?
Here is what I am trying to do:
public File savedHashMaps = new File("SavedHashMaps.list");
// in my case, the object is 'Location' from an implemented API
public Map<Location, Long> map = new HashMap<Location, Long>();
public void saveMaps() {
Properties prop = new Properties();
try {
if (!map.isEmpty()) {
prop.load(new FileInputStream(savedHashMaps));
prop.putAll(map);
prop.store(new FileOutputStream(savedHashMaps), null);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadMaps() {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(savedHashMaps));
if (!prop.isEmpty()) {
map.putAll((Map)prop);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 4
Views: 9032
Reputation: 1057
Using an ObjectInput/OutputStream
public File savedHashMaps = new File("SavedHashMaps.list");
public Map<Location, Long> map = new HashMap<Location, Long>();
public void saveMaps() {
try {
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(savedHashMaps));
oos.writeObject(map);
oos.close();
} catch (Exception e) {
// Catch exceptions
}
}
public void loadMaps() {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(savedHashMaps));
Object readMap = ois.readObject();
if(readMap != null && readMap instanceof HashMap) {
map.putAll((HashMap) readMap);
}
ois.close();
} catch (Exception e) {
// Catch exceptions
}
}
This is from memory, so sorry for errors, however this will save and reload all your Location, Long mappings. Also as a note, the Location class must implement Serializable
(or have a super-class that implements it)(It's a marker interface (See java.dzone.com/articles/marker-interfaces-java) so you just add implements Serializable
).
Upvotes: 2