0

How do you read/write a Map, specifically a LinkedHashMap, from/to a text file? I've tried to use the Iterable interface, but that doesn't work because i have Map and Iterable can only take one argument.

Map code:

Map<String, String> m1 = new LinkedHashMap<String, String>(16, 0.75f, true);

m1.put("John Smith", "555-555-5555");
m1.put("Jane Smith", "444-444-4444");

I know I have to create a PrintWriter + BufferedWriter/PrintReader + BufferedReader objects to read/write to this text file, and then use some version of the hasNext() method to read until the file ends, I just am not sure how. Please help!

EDIT: I can't use the Serializable interface for this either, because I'm trying to write a Map to the text file, not individual entries, and there's no indexOf() method for Maps.

John Smith
  • 23
  • 6
  • You are just trying to write every `Key, value` to a text file like seperate by something? – 3kings Apr 30 '16 at 23:13
  • Yeah that's what I'm trying to do. If I could just print the entire Map to the text file that would work as well. – John Smith May 02 '16 at 01:17

1 Answers1

0

Because you're trying to write your entire Map to the file and not individual entries you could use writeObject() and readObject() like this:

Map<String, String> m1 = new LinkedHashMap<String, String>(16, 0.75f, true);

m1.put("John Smith", "555-555-5555");
m1.put("Jane Smith", "444-444-4444");

//Write to file
FileOutputStream fout = new FileOutputStream("file.out");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(m1);

//Read from file
FileInputStream fin = new FileInputStream("file.out");
ObjectInputStream ois = new ObjectInputStream(fin);
Map<String, String> m2 = (LinkedHashMap<String, String>) ois.readObject();

Hope this helps.

Diogo Rocha
  • 9,759
  • 4
  • 48
  • 52