Search code examples
javahashmapfileinputstream

Save and read hashmap to file?


I want to write and read this hashmap to and from a txt file. This is what i have tried:

Main class:

    SaveRead xd = new SaveRead();
    HashMap <String,Integer>users = new HashMap<String,Integer>();

//e gets called on start

    private Object e() throws ClassNotFoundException, FileNotFoundException, IOException {
        return xd.readFile();
    }

    public void onFinish() {
          try {
            xd.saveFile(users);
        } catch (IOException e) {
        }
    }

//SaveRead class:

public class SaveRead implements Serializable{

    public void saveFile(HashMap<String, Integer> users) throws IOException{
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("/Users/Konto/Documents/scores.txt"));
    outputStream.writeObject(users);
}

    public HashMap<String, Integer> readFile() throws ClassNotFoundException, FileNotFoundException, IOException{
        Object ii = new ObjectInputStream(new FileInputStream("/Users/Konto/Documents/scores.txt")).readObject();
        return (HashMap<String, Integer>) ii;
    }
}

Does this seem ok? When it try to read the file i dont get the desired result. Is there any better way going about it?


Solution

  • It is probably because you are not closing your streams, so the contents are not being flushed to disk. You can clean this up with the try-with-resources statement (available in Java 7+). Here's a compilable example:

    public class SaveRead implements Serializable
    {
        private static final String PATH = "/Users/Konto/Documents/scores.txt";
    
        public void saveFile(HashMap<String, Integer> users)
                throws IOException
        {
            try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH))) {
                os.writeObject(users);
            }
        }
    
        public HashMap<String, Integer> readFile()
                throws ClassNotFoundException, IOException
        {
            try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH))) {
                return (HashMap<String, Integer>) is.readObject();
            }
        }
    
        public static void main(String... args)
                throws Exception
        {
            SaveRead xd = new SaveRead();
    
            // Populate and save our HashMap
            HashMap<String, Integer> users = new HashMap<>();
            users.put("David Minesote", 11);
            users.put("Sean Bright", 22);
            users.put("Tom Overflow", 33);
    
            xd.saveFile(users);
    
            // Read our HashMap back into memory and print it out
            HashMap<String, Integer> restored = xd.readFile();
    
            System.out.println(restored);
        }
    }
    

    Compiling and running this outputs the following on my machine:

    {Tom Overflow=33, David Minesote=11, Sean Bright=22}