Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Writing/Reading a Map from disk

I have a data structure that I would like to be able to write to a file before closing the program, and then read from the file to re-populate the structure the next time the application starts.

My structure is HashMap<String, Object>. The Object is pretty simple; For member variables it has a String, and two small native arrays of type Boolean. This is a real simple application, and I wouldn't expect more than 10-15 <key,value> pairs at one time.

I have been experimenting (unsuccessfully) with Object input/output streams. Do I need to make the Object class Serializable?

Can you give me any suggestions on the best way to do this? I just need a push in the right direction. Thanks!

EDIT: Well I feel dumb still, I was writing from one map and reading into another map, and then comparing them to check my results. Apparently I was comparing them wrong. Sigh.

like image 813
jazz99 Avatar asked Jan 19 '11 16:01

jazz99


1 Answers

If you aren't concerned about Object particularly , you just need key value pair of String,String then I would suggest you to go for java.util.Properties. otherwise here you go

        Map map = new HashMap();
        map.put("1",new Integer(1));
        map.put("2",new Integer(2));
        map.put("3",new Integer(3));
        FileOutputStream fos = new FileOutputStream("map.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(map);
        oos.close();

        FileInputStream fis = new FileInputStream("map.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Map anotherMap = (Map) ois.readObject();
        ois.close();

        System.out.println(anotherMap);
like image 121
jmj Avatar answered Oct 12 '22 05:10

jmj