Java:从磁盘写入/读取映射 [英] Java: Writting/Reading a Map from disk

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

问题描述

我是新的Java,所以我不知道最好的方法做到这一点。我有一个数据结构,我希望能够在关闭程序之前写入文件,然后从文件读取,以在下次应用程序启动时重新填充结构。

I am new to Java so I am not sure about the best way to do this. 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< String,Object> 。对象很简单;对于成员变量,它有一个String,和两个类型为Boolean的小本地数组。这是一个真正的简单应用程序,我不会期望超过10-15 < key,value> 对。

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!

编辑:我觉得笨拙,我是从一张地图写作,阅读另一张地图,然后比较它们来检查我的结果。显然我是比较他们错了。 Sigh。

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天全站免登陆