Java:从磁盘写入/读取地图 [英] Java: Writing/Reading a Map from disk

查看:25
本文介绍了Java:从磁盘写入/读取地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据结构,我希望能够在关闭程序之前将其写入文件,然后从文件中读取以在应用程序下次启动时重新填充该结构.

I have a data structure that I would like to be able to write to a file before closing the program, and then read from the file to re-populate the structure the next time the application starts.

我的结构是HashMap.对象非常简单;对于成员变量,它有一个字符串和两个布尔类型的小型本机数组.这是一个真正简单的应用程序,我不希望一次超过 10-15 个 对.

My structure is HashMap<String, Object>. The Object is pretty simple; For member variables it has a String, and two small native arrays of type Boolean. This is a real simple application, and I wouldn't expect more than 10-15 <key,value> pairs at one time.

我一直在尝试(失败)对象输入/输出流.我需要使 Object 类可序列化吗?

I have been experimenting (unsuccessfully) with Object input/output streams. Do I need to make the Object class Serializable?

你能就最好的方法给我任何建议吗?我只需要朝着正确的方向推动.谢谢!

Can you give me any suggestions on the best way to do this? I just need a push in the right direction. Thanks!

嗯,我还是觉得很傻,我从一张地图上写出来,然后读入另一张地图,然后比较它们以检查我的结果.显然我比较他们错了.叹气.

Well I feel dumb still, I was writing from one map and reading into another map, and then comparing them to check my results. Apparently I was comparing them wrong. Sigh.

推荐答案

如果你不是特别关心 Object ,你只需要 String,String 的键值对,那么我建议你去java.util.Properties.否则你去

If you aren't concerned about Object particularly , you just need key value pair of String,String then I would suggest you to go for java.util.Properties. otherwise here you go

        Map map = new HashMap();
        map.put("1",new Integer(1));
        map.put("2",new Integer(2));
        map.put("3",new Integer(3));
        FileOutputStream fos = new FileOutputStream("map.ser");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(map);
        oos.close();

        FileInputStream fis = new FileInputStream("map.ser");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Map anotherMap = (Map) ois.readObject();
        ois.close();

        System.out.println(anotherMap);

这篇关于Java:从磁盘写入/读取地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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