java 如何读写一个HashMap文件?

bybem2ql  于 2023-02-02  发布在  Java
关注(0)|答案(6)|浏览(122)

我有以下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,如果我简单地这样做:

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

这不会以我保存它的格式给出对象。它返回一个包含15个空元素和第3个元素的〈mylist,[a,b,c]〉对的表。我希望它只返回一个包含我最初提供给它的值的元素。
//如何将相同的对象读回HashMap?
好吧根据杰姆的笔记这似乎是正确的解释:

    • ObjectOutputStream以ObjectInputStream能够理解的反序列化格式序列化对象(在本例中为HashMap),并对任何可序列化的对象通用地执行此操作。如果希望它以所需的格式序列化,则应编写自己的序列化程序/反序列化程序。**
  • 就我而言:当我从文件中读回Object时,我只是在HashMap中迭代这些元素中的每一个,并获取数据,然后对它做任何我想做的事情(它只在有数据的地方进入循环)。

谢谢你,

vwkv1x7d

vwkv1x7d1#

你似乎混淆了HashMap的内部表示和HashMap的行为。集合是相同的。下面是一个简单的测试来证明这一点。

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

cs7cruho2#

我相信你正在犯一个常见的错误。你在使用后忘记关闭流!

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

wooyq4lh3#

也可以使用JSON文件读写MAP对象。
将Map对象写入JSON文件

ObjectMapper mapper = new ObjectMapper();

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "Suson");
    map.put("age", 26);

    // write JSON to a file
    mapper.writeValue(new File("c:\\myData.json"), map);

从JSON文件读取Map对象

ObjectMapper mapper = new ObjectMapper();

        // read JSON from a file
        Map<String, Object> map = mapper.readValue(
                new File("c:\\myData.json"),
                new TypeReference<Map<String, Object>>() {
        });

        System.out.println(map.get("name"));
        System.out.println(map.get("age"));

并从Jackson导入ObjectMapper,然后将代码放入try catch块中

mefy6pfw

mefy6pfw4#

您的第一行:

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

让我犹豫了一下,因为值不能保证是Serializable,因此可能不能正确地写出来。你应该真正地将对象定义为HashMap<String, Serializable>(或者如果你愿意,简单的Map<String, Serializable>)。
我还将考虑以简单的文本格式(如JSON)序列化Map,因为您正在进行简单的String -> List<String>Map。

tkqqtvp1

tkqqtvp15#

我相信您已经得到了所保存的内容。在保存之前检查过Map了吗?在HashMap中:

/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 16;

例如,默认的HashMap将从16 null开始。您使用了其中一个存储桶,因此在保存时只剩下15 null,这是您加载时得到的结果。请尝试检查fileObj.keySet().entrySet().values()以查看您所期望的结果。
HashMap的设计目的是在内存不足的情况下提高速度。有关详细信息,请参阅Wikipedia's Hash table条目。

z9zf31ra

z9zf31ra6#

相同的数据(如果要写入文本文件)

public void writeToFile(Map<String, List<String>> failureMessage){
    if(file!=null){
        try{
           BufferedWriter writer=new BufferedWriter(new FileWriter(file, true));
            for (Map.Entry<String, List<String>> map : failureMessage.entrySet()) {
                writer.write(map.getKey()+"\n");
                for(String message:map.getValue()){
                    writer.write(message+"\n");
                }
                writer.write("\n");
            }
            writer.close();
        }catch (Exception e){
            System.out.println("Unable to write to file: "+file.getPath());
            e.printStackTrace();
        }
    }
}

相关问题