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

时间:2018-11-06 08:17:39

标签: java arrays hashmap

我使用以下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 个答案:

答案 0 :(得分:2)

您的代码似乎不会将最后一个键值对添加到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());
                }
相关问题