0

I have used a HashMap to store information that I needed on a text document using the code below, how would I now go about loading the data back into my program, currently the saving works just fine.

The text file currently stores

KEY=VALUE

so for example my text file would be:

1=value
2=value
3=value

The current way I save things to this file (not sure if relevant) is this:

    public void save(HashMap<Integer, String> map) {
        try {
            File zone1 = new File("zones/zone1");
            FileOutputStream fileOut = new FileOutputStream(zone1);
            PrintWriter print = new PrintWriter(fileOut);
            for (Map.Entry<Integer, String> m : map.entrySet()) {
                print.println(m.getKey() + "=" + m.getValue());
            }

            print.flush();
            print.close();
            print.close();
        } catch (Exception e) {
        }
    }
  • 2
    Refer this https://stackoverflow.com/questions/1318347/how-to-use-java-property-files. – Sambit Apr 26 '19 at 17:07
  • 2
    It looks like you're attempting to recreate something that already exists: [java.util.Properties](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Properties.html) – Jacob G. Apr 26 '19 at 17:07

2 Answers2

0

If you really want to that by hand (as the comments have stated, this is already implemented in java.util.Properties), refer to:

java.io.BufferedReader::readLine java.lang.String::split

tjanu
  • 172
  • 2
  • 11
0

An example to read key value from file and to store key value inside HashMap.

try (InputStream input = new FileInputStream("path/to/file")) {
        Map<Integer,String> loadedFromTextFileHashMap=new HashMap<>();
        Properties prop = new Properties();
        prop.load(input);
        prop.forEach((key, value) -> loadedFromTextFileHashMap.put(Integer.valueOf(key.toString()), value.toString()));
} catch (IOException io) {
        io.printStackTrace();
}
Joy
  • 394
  • 2
  • 9