Search code examples
javaruntimestore

Storing a Map between Runtimes


I have been reading some posts on how to store data between runtimes, between HBase, Serialization, and other stuff, but is there a way to store a Map(Object, Set of difObject) easily? I have been watching videos and reading posts and I just havent been able to wrap my brain around it, also wherever I store the data cannot be human readable as it has personal information on it.


Solution

  • Use java.io.ObjectOutputStream and java.io.ObjectInputStream to persist Java objects (in your case: write/read the Map). Make sure that all objects you're persisting implement Serializable.

    Example: writing data(marshalling)

    Map<String, Set<Integer>> map = new HashMap<String, Set<Integer>>();
    map.put("Foo", new HashSet<Integer>(Arrays.asList(1, 2, 3)));
    map.put("Bla", new HashSet<Integer>(Arrays.asList(4, 5, 6)));
    
    File file = new File("data.bin");
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    try {
        out.writeObject(map);
        out.flush();
    } finally {
        out.close();
    }
    

    Reading the stored data (unmarshalling)

    File file = new File("data.bin");
    if (file.exists()) {
        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
        try {
            Map<String, Set<Integer>> read = (Map<String, Set<Integer>>) in.readObject();
            for (String key : read.keySet()) {
                System.out.print(key + ": ");
                Set<Integer> values = read.get(key);
                for (Integer value : values) {
                    System.out.print(value + " ");
                }
                System.out.println();
            }
        } finally {
            in.close();
        }
    }