2016-04-30 135 views
0

您如何從/向文本文件讀取/寫入地圖,特別是LinkedHashMap?我嘗試過使用Iterable接口,但這不起作用,因爲我有Map並且Iterable只能接受一個參數。將LinkedHashMap寫入文本文件?

地圖代碼:

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"); 

我知道我必須創建一個PrintWriter +的BufferedWriter/PrintReader + BufferedReader中的對象進行讀/寫該文本文件,然後使用hasNext的某些版本()方法直到文件結束閱讀,我只是不知道如何。請幫忙!

編輯:我無法使用可序列化的接口,因爲我試圖寫一個地圖到文本文件,而不是單個的條目,並且沒有map的indexOf()方法。

+0

你只是試圖將每個'Key,value'寫入一個文本文件,就像是用某種東西分開的東西? – 3kings

+0

是的,這就是我想要做的。如果我可以將整個地圖打印到文本文件中,那也可以。 –

回答

0

因爲你想你的整個地圖寫入文件,而不是單個條目,你可以使用writeObject()readObject()這樣的:

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(); 

希望這有助於。