代码之家  ›  专栏  ›  技术社区  ›  plaidshirt

从文本文件中获取单行和多行值

  •  1
  • plaidshirt  · 技术社区  · 7 年前

    Java 从文本文件中获取特定值的代码,该文本文件包含不同顺序的键值对。

                   if(nfo_file.exists() && !nfo_file.isDirectory()) {
                        Scanner scanner = new Scanner(nfo_file);
                        Map<String, String> values = new HashMap<>();
                        String line, key = null, value = null;
                        while (scanner.hasNextLine()) {
                            line = scanner.nextLine();
                            if (line.contains(":")) {
                                if (key != null) {
                                    values.put(key, value.trim());
                                }
                                int indexOfColon = line.indexOf(":");
                                key = line.substring(0, indexOfColon);
                                value = line.substring(indexOfColon + 1);
                            } else {
                                value += " " + line;
                            }
                        }
    
                        for (Map.Entry<String, String> entry : values.entrySet()) {
                            if (entry.getKey().startsWith("Description")) {
                                nfodata[0] = entry.getValue();
                            }
    

    Num: 10101
    Name: File_8
    Description: qwertz qwertz
    qwertz (qwertz) ztrewq?
    Neque porro quisquam est qui
    Quantity: 2
    

    它在某些情况下不起作用,它不读取单行,有时只读取多行值的第一行。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Eran    7 年前

    看起来您的代码不会将最后一个键值对添加到 Map .

    尝试:

                    while (scanner.hasNextLine()) {
                        line = scanner.nextLine();
                        if (line.contains(":")) {
                            if (key != null) {
                                values.put(key, value.trim());
                                key = null;
                                value = null;
                            }
                            int indexOfColon = line.indexOf(":");
                            key = line.substring(0, indexOfColon);
                            value = line.substring(indexOfColon + 1);
                        } else {
                            value += " " + line;
                        }
                    }
                    if (key != null) {
                        values.put (key, value.trim());
                    }