2015-02-23 81 views
-1

我在我的Java代碼中序列化哈希映射並將其寫入文件。反序列化時,文件包含多個值,但它只返回最上面的鍵和值對。誰能告訴我爲什麼?這裏是我的反序列化的Java代碼:java中hashmap的反序列化

public static void main(String[] args) throws IOException, ClassNotFoundException { 

    HashMap<String, String> data = new HashMap<Integer, String>(); 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("F:\\f.txt")); 

    data = (HashMap<String, String>) in.readObject(); 

    for (Map.Entry entry : data.entrySet()) { 
     System.out.println("key" + entry.getKey()); 
     System.out.println("value" + entry.getValue()); 
    } 

} 

這裏是我的序列化代碼

public class SerializeObject implements Serializable { 


    public static void main(String[] args) throws IOException, ClassNotFoundException 
    { 
      HashMap<String,String> map = new HashMap<String,String>(); 
      map.put("Monday","first"); 
      map.put("Tuesday","Second"); 
      map.put("Wednesday","Third"); 
      FileOutputStream fout=new FileOutputStream("F:\\f.txt",true); 
      ObjectOutputStream out=new ObjectOutputStream(fout); 
      out.writeObject(map); 
      out.flush(); 

     } 
    } 

反序列化它之後返回只在週一和第一

+0

您使用什麼代碼來序列化它? f.txt的內容是什麼?請修正您的格式。 – 2015-02-23 11:15:46

+0

序列化完成後執行反序列化工作正常......您的映射關鍵字是否從字符串切換爲整數? – 2015-02-23 11:50:20

+0

嗨...對不起,這只是我的錯誤 – wazza 2015-02-23 11:54:57

回答

0

應關閉流。 out.flush()可能不足以確保將所有剩餘數據寫入磁盤。確保使用try-with-resource陳述的簡單方法:

public static void main(String[] args) throws IOException, ClassNotFoundException 
{ 
     HashMap<String,String> map = new HashMap<String,String>(); 
     map.put("Monday","first"); 
     map.put("Tuesday","Second"); 
     map.put("Wednesday","Third"); 
     try (
      FileOutputStream fout=new FileOutputStream("F:\\f.txt",true); 
      ObjectOutputStream out=new ObjectOutputStream(fout); ) 
     { 
      out.writeObject(map); 
     } 
}