Ericson Willians
Ericson Willians

Reputation: 7845

Java (HashMap) - How to save and load an entrySet()?

I have 2 hashmaps and I want both to be saved when the menu button is clicked, and I want to be able to load them (In the example I'm saving just one).

void saveHash(HashMap<String, Object> hash, HashMap<String, Object> logicalMatrix2) {
    JFrame parentFrame = new JFrame();

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Especifique um diretório:");
    fileChooser.setAcceptAllFileFilterUsed(false);

    int userSelection = fileChooser.showSaveDialog(parentFrame);

    if (userSelection == JFileChooser.APPROVE_OPTION) {
        File fileToSave = new File(fileChooser.getSelectedFile() + ".alg");
        Set<Entry<String, Object>> entry = hash.entrySet();
        FileWriter outFile;
        try {
            outFile = new FileWriter(fileToSave.getAbsolutePath());
            PrintWriter out = new PrintWriter(outFile);
            out.println(entry);
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
}

With this I can save the entrySet() in a txt file, but then I have no idea of how to load this content back. The software will start with the HashMap empty, and then, through the loading process, I want to be able to fill the keys and their respective values accordingly. But, considering that it was saved in a txt file, how could I run "reading loops" through it to identify unknown keys? The problem gets more complicated when we consider that the value of each key is an ArrayList.

Thank you very much!

Upvotes: 0

Views: 787

Answers (2)

Jeff Olson
Jeff Olson

Reputation: 6463

Besides using Serialization, which others have mentioned, another route to explore would be using JSON as a persistent format. You could use Gson to accomplish this.

Upvotes: 0

NullPointerException
NullPointerException

Reputation: 184

Potentially the simplest route is to use an ObjectOutputStream instead of PrintWriter and you can read the results using an ObjectInputStream.
This is assuming that the Objects contained in your HashMap are either Serializable or Externalizable.
I would just serialize the HashMap itself instead of the entrySet. There are a number of considerations (versioning, transient objects, Enum constants, etc.) when using object serialization, so I would suggest you do some reading about the subject.

XMLEncoder and XMLDecoder may allow for more portability if you ever need to read the files outside the Java environment or want them to be human readable.

Upvotes: 2

Related Questions