如何读取和写入 HashMap 到文件? [英] How to read and write a HashMap to a file?

查看:23
本文介绍了如何读取和写入 HashMap 到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 HashMap:

HashMap<String,Object> fileObj = new HashMap<String,Object>();

ArrayList<String> cols = new ArrayList<String>();  
cols.add("a");  
cols.add("b");  
cols.add("c");  
fileObj.put("mylist",cols);  

我将其写入文件如下:

File file = new File("temp");  
FileOutputStream f = new FileOutputStream(file);  
ObjectOutputStream s = new ObjectOutputStream(f);          
s.writeObject(fileObj);
s.flush();

现在我想把这个文件读回一个HashMap,其中Object是一个ArrayList.如果我只是这样做:

Now I want to read this file back to a HashMap where the Object is an ArrayList. If i simply do:

File file = new File("temp");  
FileInputStream f = new FileInputStream(file);  
ObjectInputStream s = new ObjectInputStream(f);  
fileObj = (HashMap<String,Object>)s.readObject();         
s.close();

这并没有以我保存它的格式给我对象.它返回一个包含 15 个空元素和 <mylist,[a,b,c] > 在第三个元素处配对.我希望它只返回一个具有我一开始提供给它的值的元素.
//如何将同一个对象读回HashMap?

This does not give me the object in the format that I saved it in. It returns a table with 15 null elements and the < mylist,[a,b,c] > pair at the 3rd element. I want it to return only one element with the values I had provided to it in the first place.
//How can I read the same object back into a HashMap ?

好的,所以根据 Cem 的注释:这似乎是正确的解释:

OK So based on Cem's note: This is what seems to be the correct explanation:

ObjectOutputStream 以 ObjectInputStream 能够理解反序列化的任何格式序列化对象(在这种情况下为 HashMap),并且通常对任何 Serializable 对象执行此操作.如果您希望它以您希望的格式序列化,您应该编写自己的序列化器/反序列化器.

在我的例子中:当我从文件中读回对象并获取数据并用它做任何我想做的事情时,我只需遍历 HashMap 中的每个元素.(它只在有数据的地方进入循环).

谢谢,

推荐答案

您似乎将 HashMap 的内部表示与 HashMap 的行为方式混淆了.集合是一样的.这里有一个简单的测试来证明给你看.

You appear to be confusing the internal resprentation of a HashMap with how the HashMap behaves. The collections are the same. Here is a simple test to prove it to you.

public static void main(String... args)
                            throws IOException, ClassNotFoundException {
    HashMap<String, Object> fileObj = new HashMap<String, Object>();

    ArrayList<String> cols = new ArrayList<String>();
    cols.add("a");
    cols.add("b");
    cols.add("c");
    fileObj.put("mylist", cols);
    {
        File file = new File("temp");
        FileOutputStream f = new FileOutputStream(file);
        ObjectOutputStream s = new ObjectOutputStream(f);
        s.writeObject(fileObj);
        s.close();
    }
    File file = new File("temp");
    FileInputStream f = new FileInputStream(file);
    ObjectInputStream s = new ObjectInputStream(f);
    HashMap<String, Object> fileObj2 = (HashMap<String, Object>) s.readObject();
    s.close();

    Assert.assertEquals(fileObj.hashCode(), fileObj2.hashCode());
    Assert.assertEquals(fileObj.toString(), fileObj2.toString());
    Assert.assertTrue(fileObj.equals(fileObj2));
}

这篇关于如何读取和写入 HashMap 到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆