【问题标题】:Storing a Map between Runtimes在运行时之间存储映射
【发布时间】:2014-02-07 01:57:53
【问题描述】:

我一直在阅读一些关于如何在运行时之间、HBase、序列化和其他东西之间存储数据的文章,但是有没有一种方法可以轻松地存储 Map(Object, Set of difObject)?我一直在看视频和阅读帖子,但我无法将我的大脑包裹起来,而且我存储数据的任何地方都无法被人类阅读,因为它上面有个人信息。

【问题讨论】:

标签: java runtime store


【解决方案1】:

使用java.io.ObjectOutputStreamjava.io.ObjectInputStream 来持久化Java 对象(在您的情况下:写入/读取Map)。确保你持久化的所有对象都实现了Serializable

示例:写入数据(编组)

Map<String, Set<Integer>> map = new HashMap<String, Set<Integer>>();
map.put("Foo", new HashSet<Integer>(Arrays.asList(1, 2, 3)));
map.put("Bla", new HashSet<Integer>(Arrays.asList(4, 5, 6)));

File file = new File("data.bin");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
try {
    out.writeObject(map);
    out.flush();
} finally {
    out.close();
}

读取存储的数据(解组)

File file = new File("data.bin");
if (file.exists()) {
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
    try {
        Map<String, Set<Integer>> read = (Map<String, Set<Integer>>) in.readObject();
        for (String key : read.keySet()) {
            System.out.print(key + ": ");
            Set<Integer> values = read.get(key);
            for (Integer value : values) {
                System.out.print(value + " ");
            }
            System.out.println();
        }
    } finally {
        in.close();
    }
}

【讨论】:

  • 谢谢,这正是我所需要的。 +1000000000
  • 还有一个问题,我可以做一个与 .bin 不同的扩展名吗?
  • 是的,扩展名根本不重要,你可以选择任何你想要的文件名和扩展名。
猜你喜欢
  • 2015-04-08
  • 2015-10-17
  • 2018-09-13
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
相关资源
最近更新 更多