【问题标题】:Deserialization of hashmap in javajava中hashmap的反序列化
【发布时间】:2015-02-23 11:12:33
【问题描述】:

我在我的 Java 代码中序列化一个哈希映射并将它写入一个文件。在反序列化时,文件包含多个值,但它只返回最上面的键和值对。谁能告诉我为什么?这是我的反序列化 Java 代码:

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

        }
  }

反序列化后它只返回星期一和第一个

【问题讨论】:

  • 你用什么代码来序列化它? f.txt 的内容是什么?请修正您的格式。
  • 在序列化工作正常后执行反序列化...您的地图键也从字符串切换到整数?!
  • 嗨...对不起,这只是我的错误

标签: java serialization hashmap


【解决方案1】:

您应该关闭您的信息流。 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);  
         }
}

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2013-07-26
    • 2016-09-16
    • 2012-05-24
    相关资源
    最近更新 更多