2017-01-12 10 views
-2

このハッシュマップをtxtファイルとの間で読み書きしたいとします。ハッシュマップを保存してファイルに読み込みますか?

メインクラス:eが開始

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

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

// SaveReadクラスに呼び出さ

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

//:

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

これは思えないこれは私が試したものですOK?ファイルを読み込もうとすると、望みの結果が得られません。それについてもっと良い方法はありますか?

+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} 
関連する問題