14

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jazz99
  • 143
  • 1
  • 1
  • 5
  • 1
    HashMap is already Serializable. What went wrong when you tried to write it to an ObjectOutputStream? – finnw Jan 19 '11 at 16:59
  • Object input/output streams are not the only way to go. Do you specifically want advice on using them? Or on I/O in general? – Raedwald Jan 19 '11 at 17:02
  • @Raedwald - Really just looking for the best way to go for a simple app. Google led me Object streams. – jazz99 Jan 19 '11 at 17:13
  • @finnw - I coded it from examples found on the web, but they were all examples and I am dealing with . My Object class was Serializable, but I'm not sure I'm implementing it correctly. First time! – jazz99 Jan 19 '11 at 17:16
  • There's an interesting library for this in 2017: http://www.mapdb.org/ – Sridhar Sarnobat Oct 16 '17 at 21:29

7 Answers7

34

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);
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    I was definitely not using the .ser extension, will try that. Thanks – jazz99 Jan 19 '11 at 17:22
  • The .ser extension seems to have fixed my issue. Now I will have to go read about why that is. You get the win. – jazz99 Jan 19 '11 at 17:56
  • 7
    `.ser` shouldn't be the core issue, you can give any extension here also no extension would also work here – jmj Jan 19 '11 at 18:08
  • 3
    Yep, the `.ser` extension is meaningless to Java. – Jé Queue Jan 19 '11 at 18:14
  • 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. – jazz99 Jan 19 '11 at 18:39
  • @JigarJoshi don't you need to close both stream ? fos.close(); and fis.close(); ? Or closing the objectstrem closes the filestream ? – HpTerm Oct 18 '13 at 12:15
  • You da real mvp Joshi! Danke! – Sipty Jul 07 '15 at 13:44
2

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.

k1eran
  • 4,492
  • 8
  • 50
  • 73
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
2
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();
Jé Queue
  • 10,359
  • 13
  • 53
  • 61
0

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();
    }

}
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Kumar Gaurav
  • 107
  • 1
  • 7
0

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.

David Weiser
  • 5,190
  • 4
  • 28
  • 35
0

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.

Speck
  • 2,259
  • 1
  • 20
  • 29
  • why is csv a better solution than serialization? serialization involves not extra code, whereas you would have to get/write the csv formatting/parsing code yourself. – jtahlborn Jan 19 '11 at 17:35
  • We tend to avoid Serializable objects unless we absolutely have to use them. There's more to them than people realize. Like Raedwald I'm influenced by Bloch's "Effective Java". – Speck Jan 19 '11 at 18:20
  • 2
    csv has its own pitfalls. how do you escape the delimiter? how do you escape the escape? etc... still don't buy it as a better alternative for something this simple. – jtahlborn Jan 20 '11 at 03:50
  • For something this simple either choice is probably acceptable. Dealing with delimiters is hardly complex. I'm just saying people need to be aware of the costs of Serialization. – Speck Jan 20 '11 at 14:45
  • We don't know anything about his application. While it is a good idea to suggest other means of serialization (CSV is also serialization, just not binary), it should not be an answer, but happen in the comments. Furthermore this should be a follow up on a curious question on his application. – Mads Buch Dec 15 '17 at 16:14
0

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • 1
    I agree that Serializable is not effective for extremely durable data, but for temporal durability without the need for query or data management, I think it works well. – Jé Queue Jan 19 '11 at 18:16