简体   繁体   中英

Reading records from a text file in Java

I have a text file that contains multiple records in the below format

After reading the file, How do I store all these records, so that I can access and manipulate them, such as updating the fields in the record.The field and the field content are separated by multiple spaces.And the new records are separated by blank line

birthday      27-03-1984
address       27 Drew Street, Elwood,
              VIC
Postcode      3184
phone         0067282

name          Carlos
birthday      27-03-1988
address       27 langhlam, Southbank,
              VIC
Postcode      3184
phone         00672165```

Looks like tab-separated data. Use a CSV parser to read these, such as univocity

There are libraries like mentioned, but for this simple case can be done easily using java.util only:

public class PersonsReader {
    public static void main(String[] args) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get("inputFile.txt")));
        List<Person> persons = Arrays.stream(content.split("\n\n"))
                .map(PersonsReader::toPerson).collect(Collectors.toList());
        // use persons list here
    }

    private static Person toPerson(String personData) {
        Map<String, String> keyValue = Arrays.stream(personData.split("\n"))
                .collect(Collectors.toMap(
                        line -> line.split("\\s+")[0],
                        line -> line.split("\\s+")[1]));
        return new Person(keyValue.get("name"),
                keyValue.get("birthday"),
                keyValue.get("address"),
                keyValue.get("Postcode"),
                keyValue.get("phone"));
    }
}

Note that some of the keys do not exist in keyValue so Person constructor gets null for some of the parameters. Also, in Person constructor you can convert parameter to Integer if needed (and check first if null ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM