【问题标题】:Store Map entries in file and read those back in将 Map 条目存储在文件中并将其读回
【发布时间】: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


【解决方案1】:
public Map<String, List<String>> readSubCats() throws IOException {
    Map<String, List<String>> ret = new HashMap<String, List<String>>();
    BufferedReader in = new BufferedReader(new FileReader("subcats.txt"));
    String line = null;
    while ((line = in.readLine()) != null) {
        int i = line.indexOf("=");
        // if i < 0 throw an Exception
        ret.put(line.substring(0, i), Arrays.asList(line.substring(i + 2, line.length() - 1).split(",\\t")));
    }
    in.close();
    return ret;
}

这只有在列表中的字符串中没有任何\n\t 并且键中没有= 时才有效,其他字符都可以。

注意split 需要一个正则表达式,正则表达式中的制表符类似于Java 中的\t,但是因为\ 是Java 中的转义字符,我们需要转义自身,从而导致\\t。如果你想用\分割,那么你必须写split("\\\\"),因为\也是正则表达式中的转义字符。

【讨论】:

  • 抱歉回复晚了,忙了几天。按照建议使用您的代码,并像魅力一样工作。非常感谢。
  • @markknaap 不客气。如果它解决了您的问题,请接受它作为答案(灰色复选标记)。
猜你喜欢
  • 2020-10-18
  • 2015-02-24
  • 2018-05-30
  • 2020-04-29
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
相关资源
最近更新 更多