简体   繁体   中英

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.

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);
Map m = new HashMap();
// let's use untyped and autoboxing just for example
m.put("One",1);
m.put("Two",2);

ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("foo.ser")
);
oos.writeObject(m);
oos.flush();
oos.close();

Yes, your objects will need to implement Serializable in order to be serialized by the default Java mechanism. HashMap and String already implement this interface and thus can be serialized successfully.

Take a look at Sun's own Serialization tutorial - it's quite short and I think should cover everything you need for your simple case. (You should just be able to serialise the Map object to the stream, and then read it back in on subsequent runs).

If you do run into problems, try serializing a simple HashMap<String, String> with some dummy values. If this succeeds, you'll know that the problem lies (somehow) with your own class' serializability; alternatively, if this doesn't work you can focus on the basic structure before throwing your own class into the mix.

Post back if you have any more specific problems that you can't figure out on your own.

Yes, if you want to write an object to the file system, that object must implement Serializeable . Here is a tutorial that should help you out.

Don't bother with making it Serializable until you understand more about what that's used for. You want to look at FileWriter and google "java file io" A good way to write this data is as CSV.

eg.

key1,key2,key3 valuea1,valuea2,valuea3 valueb1,valueb2,valueb3

Hope this helps.

I'd advise against using Serializable ; it is much harder to do properly than it first seems. It would seem that simply adding implements Serializable is all you need to do. But in fact this adds many restrictions on your code that are difficult to deal with in practical software development (rather than in school). To see just how horrible these restrictions are, see the book Effective Java (second edition) by Bloch.

SERIALIZE A HASHMAP: This code is working fine , I have implemented and used in my app. Plz make ur functions accordingly for saving map and retrieving map.

Imp thing is, you need to make confirm that the objects you are putting as value in map must be serializable , means they should implement serailizbele interface. ex. Map<.String,String> hashmap=new HashMap<.String,String>().. here in this line ...map and string both are implictly serializable , so we dont need to implement serializble for these explicitly but if you put your own object that must be serializable.


public static void main(String arr[])
{
  Map<String,String> hashmap=new HashMap<String,String>();
 hashmap.put("key1","value1");
    hashmap.put("key2","value2");
    hashmap.put("key3","value3");
    hashmap.put("key4","value4");

     FileOutputStream fos;
    try {
        fos = new FileOutputStream("c://list.ser");

    ObjectOutputStream oos = new ObjectOutputStream(fos);
     oos.writeObject(hashmap);
     oos.close();

     FileInputStream fis = new FileInputStream("c://list.ser");
     ObjectInputStream ois = new ObjectInputStream(fis);
    Map<String,String> anotherList = (Map<String,String>) ois.readObject();

     ois.close();

     System.out.println(anotherList);

 } catch (FileNotFoundException e) {e.printStackTrace();
 } catch (IOException e) {e.printStackTrace();
    } catch (ClassNotFoundException e) {e.printStackTrace();
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM