java - 如何使用 HashMap 写入和读取文件?

标签 java file dictionary hashmap

<分区>

我有一个 HashMap有两个字符串 Map<String, String> ldapContent = new HashMap<String, String> .

现在我想保存 Map在外部文件中使用 Map稍后无需再次初始化...

那么我该如何保存 Map稍后再使用它?

最佳答案

我能想到的最简单的解决方案是使用 Properties 类。

保存 map :

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();

for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
    properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream("data.properties"), null);

加载 map :

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));

for (String key : properties.stringPropertyNames()) {
   ldapContent.put(key, properties.get(key).toString());
}

编辑:

如果您的 map 包含纯文本值,则当您通过任何文本编辑器打开文件数据时它们将可见,但如果您序列化 map 则不会出现这种情况:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();

编辑2:

在保存示例中代替 for 循环(如 OldCurmudgeon 所建议的那样):

properties.putAll(ldapContent);

但是,对于加载示例,这是可以做到的最好的:

ldapContent = new HashMap<Object, Object>(properties);

关于java - 如何使用 HashMap 写入和读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747946/

相关文章:

java - 我如何以编程方式为 Spring Boot 和 Tomcat 提供 keystore 文件?

java - 文件中的字符串格式

python - 使用 arcpy Polyline 对象作为字典值时形状信息丢失

java - 使用非最终变量将 Java Map.Entry 传输到 Stream

java - 使用 Guice 在实现使用泛型时如何绑定(bind)参数化类的多个实例?

java数组按引用传递不起作用?

python - 在Python中合并多个列表中的字典

java - 如果文件不存在则创建一个文件

c# - 将二维数组写入文件的最简单方法是什么?

java - 在 Struts2 JSP 中获取 Map 的值