java - 存储运行时之间的映射

标签 java runtime store

我一直在阅读一些关于如何在运行时之间、HBase、序列化和其他东西之间存储数据的帖子,但是有没有一种方法可以轻松地存储 Map(Object, Set of difObject)?我一直在观看视频和阅读帖子,但我一直无法全神贯注,而且我存储数据的任何地方都无法让人阅读,因为它包含个人信息。

最佳答案

使用 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();
    }
}

关于java - 存储运行时之间的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21190954/

相关文章:

java - 在 Java EE 6 中生成激活 url

java - 公共(public)方法如何返回私有(private)类型?

java - int to Long 解析错误

performance - 字符串连接检查算法的运行时

python - 如何在python中另一个类的函数中获取调用者类名?

javascript - 无法使用 loadData() 在 ExtJS gridpanel 中加载数据

java - 我可以在哪里了解 JVM 调试器协议(protocol)?

C++编译时/运行时选项和参数,如何处理?

java - 如何使用 WebDriver 将字符串保存为变量,然后在另一个测试中使用 tis 变量

c# - VSIX 凭据的存储位置 - Visual Studio 2017 扩展