plaidshirt
plaidshirt

Reputation: 5671

Get single line and multiple line values from text file

I use following Java code to get specific values from a text file, which contains key-value pairs in different order.

               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();
                        }

Input text file example:

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

It doesn't work in some cases, it doesn't read one liners and sometimes read only first line of a multiline value.

Upvotes: 1

Views: 295

Answers (1)

Eran
Eran

Reputation: 393781

It looks like your code will not add the last key-value pair to the Map.

Try:

                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());
                }

Upvotes: 2

Related Questions