<分区>
我有一个 HashMap
有两个字符串 Map<String, String> ldapContent = new HashMap<String, String>
.
现在我想保存 Map
在外部文件中使用 Map
稍后无需再次初始化...
那么我该如何保存 Map
稍后再使用它?
<分区>
我有一个 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/