2017-01-12 28 views
-2

我想寫和讀取這個哈希映射到和從一個txt文件。這是我曾嘗試:保存並讀取hashmap文件?

主要類:

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

//ê被調用在啓動

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

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

// SaveRead類:

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; 
    } 
} 

這個問題似乎好?當它試圖讀取文件,我沒有得到所需的結果。有沒有更好的方法去做呢?

+1

*「我沒有得到期望的結果」 *是否有得到一個更好的問題說明的機會呢? – Tom

+1

[如何讀取和寫入HashMap到文件?](https://stackoverflow.com/questions/3347504/how-to-read-and-write-a-hashmap-to-a-file)可能的重複 – Loren

回答

2

這可能是因爲你沒有關閉你的流,所以內容沒有被刷新到磁盤。您可以使用try-with-resources statement(Java 7+中提供)進行清理。這裏有一個編譯的例子:

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

編譯和運行這個輸出我的機器上執行以下操作:

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