Java:从磁盘写入/读取映射 [英] Java: Writing/Reading a Map from disk
问题描述
我有一个数据结构,我希望能够在关闭程序之前将其写入文件,然后在下次应用程序启动时从文件中读取数据以重新填充该结构.
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和两个布尔类型的小型本机数组.这是一个真正简单的应用程序,我希望一次不会超过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.
我一直在尝试(不成功)对象输入/输出流.我需要使对象类可序列化吗?
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键值对,那么我建议您使用
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屋!