Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

How to use HashMap to write to an external txt file

public void writeAMap(HashMap<String, String> map, String filename) { if(map != null) { try (FileWriter writer = new FileWriter(filename, true)) { for(String key : map.keySet()) { String value = map.get(key); if(value == null) { System.out.println("Warning: Null response for " + key + " in writeAMap. Using a default."); value = "I don't know what you mean?"; } writer.write(key.trim()); writer.write('\n'); writer.write(value.trim()); writer.write('\n'); }
writer.close(); } catch(IOException e) { System.out.println("Problem writing file: " + filename + " in writeAMap"); } } else { System.out.println("Null map passed to writeAMap."); }

I am then calling this method in another class like the below

public void mapWrite(HashMapmap) { help.writeAMap(map, "responses.txt"); }

Then I am calling the above method to the main method like below.

HashMap key = new HashMap(); instruct.mapWrite(key);

but it isn't working, it compiles fine but it just does not to do anything.

1 Answer

I'd suggest using a debugger to help pinpoint where the code is going wrong. Particularly I'd set a breakpoint before calling the save function (or inside at the top) and examine the map to make sure it's not empty (which is not the same as being null) and has the key/value pairs you expect.

I also note that the snippets you wrote don't all have the <String, String> for the HashMap. Make sure you have that whenever you declare a HashMap to be sure the types are correct.