我有一个嵌套的MAP。我想将这些Map保存在文本文件中,然后在另一个项目中使用此文件。我可以正确保存outerMap,但是我需要一个高效的代码来将这个文件加载到同一个地图中(我使用'#'来分隔outerMap及其innerMap的键)。
Map <String, Map <String,Double>> outerMap= new HashMap<>();
Map <String,Double> innerMap= new HashMap<>();
.
.
.
PrintWriter writer = new PrintWriter("e:\\t.txt", "UTF-8");
Iterator it = outerMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
writer.println(pairs.getKey() + "#" + pairs.getValue());
}
writer.close();
答案 0 :(得分:0)
这对我来说听起来很简单。
(假设您要将文件的值加载到innerMap中)
FileInputStream inputStream = new FileInputStream("e:\\t.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String buffer;
while((buffer = reader.readLine()) != null){
String[] pairs = buffer.split("#");
innerMap.put(pairs[0],Double.parseDouble(pairs[1]));
}
在您认为必要时进行安全检查。
注意:示例代码是盲目编写的,可能会出现粗心的错误。
答案 1 :(得分:0)
关于你的评论问题:
Gson gson = new Gson();
Map<String, Map<String, Double>> outerMap = new HashMap<>();
Map<String, Double> innerMap = new HashMap<>();
innerMap.put("1", 1.0);
innerMap.put("2", 2.0);
outerMap.put("key1", innerMap);
String json = gson.toJson(outerMap);
Path path = FileSystems.getDefault().getPath("", "myfile.txt");
Files.write(path, json.getBytes("UTF-8"), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
json = new String(Files.readAllBytes(path));
outerMap = gson.fromJson(json, new TypeToken<Map<String, Map<String, Double>>>(){}.getType());
for (Map.Entry<String, Map<String, Double>> outerEntry: outerMap.entrySet()) {
System.out.println(outerEntry.getKey());
innerMap = outerEntry.getValue();
for (Map.Entry<String, Double> innerEntry: innerMap.entrySet()) {
System.out.println(" " + innerEntry.getKey() + "->" + innerEntry.getValue());
}
}
输出:
KEY1 2→2.0 1→1.0
您需要使用Gson库。
如果您不需要文本文件中的人类可读内容,您可以使用第一条评论中建议的方法:
Map<String, Map<String, Double>> outerMap = new HashMap<>();
Map<String, Double> innerMap = new HashMap<>();
innerMap.put("1", 1.0);
innerMap.put("2", 2.0);
outerMap.put("key1", innerMap);
// write to file
try (ObjectOutput objectOutputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("myfile2.txt", false)))) {
objectOutputStream.writeObject(outerMap);
} catch (Throwable cause) {
cause.printStackTrace();
}
// read from file
try (ObjectInput objectInputStream = new ObjectInputStream(new BufferedInputStream(new FileInputStream("myfile2.txt")))) {
outerMap = (Map<String, Map<String, Double>>) objectInputStream.readObject();
} catch (Throwable cause) {
cause.printStackTrace();
}
您将在'outerMap'参考上获得地图。