2015-02-23 35 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); 
     } 
}