【发布时间】:2015-05-20 20:16:34
【问题描述】:
我已经声明了一个如下所示的地图,并用值和键填充了它。
Map<String,List<String>> cat = new HashMap<String,List<String>>();
我可以成功地将它写入这样的文件:
try{
File SubCats = new File("subcats.txt");
FileOutputStream fos=new FileOutputStream(SubCats);
PrintWriter pw = new PrintWriter(fos);
for(Map.Entry<String,List<String>> m :cat.entrySet()) {
pw.println(m.getKey()+"="+m.getValue());
}
pw.flush();
pw.close();
fos.close();
}
我现在的问题是如何从文件中将其读回地图中。我正在尝试这样的事情,但不知道如何将值和键重新“放入”。
BufferedReader in = new BufferedReader(new FileReader("subcats.txt"));
String line = "";
while ((line = in.readLine()) != null) {
String parts[] = line.split("\t");
for(Map.Entry<String,List<String>> m :cat.entrySet()) {
(m.putKey(), m.putValue());
}
in.close();
}
谢谢。
【问题讨论】:
-
为什么要在标签上拆分?为什么不拆分
=,因为那是键和值之间的分隔符?为什么您认为需要迭代 map 的 entrySet 才能向 map 添加键/值对?请注意,您的策略充满了问题:如果键或值包含=,或者它包含多行怎么办?或者,如果它包含您平台的默认字符集不支持的字符?我会将映射序列化为 JSON。 -
恐怕你是完全正确的。这不起作用,因为我尝试读取的文件格式如下:Fruits=[Apple, Pear, Banana, Mango, Orange]。
-
@markknaap 看看我的回答应该可以,你的评论表明分隔符是
",\t",如果不是我可以轻松调整。
标签: java dictionary file-io hashmap bufferedreader