如何逐行拆分文件内容并保存到List

How to split file content line by line and save to List

我必须读取一个文件 people.txt 包含:

name | age | sex | address 
michael | 23 | M | germany
rachel | 25 | F | dubai

我想拆分此文件的内容并将其保存到人员列表 (List<Person>),其中只需要设置姓名和性别字段。

class Person {
    String name;
    String sex;
}

如何使用 Java 8 实现此目的?

         Files.lines(Paths.get("/your/path/here"))
              .map(line -> line.split("\s*\|\s*"))
              .map(array -> new Person(array[0], array[2]))
              .collect(Collectors.toList);

我还没有编译这个,但应该可以完成。

假设每人换行:

Files.lines(Paths.get("people.txt"))
     .skip(1) // skip the header
     .map(Person::new)
     .collect(toList());

应该有一个构造函数,它使用 String 从以下位置构造一个 Person 实例:

public Person(String s) {
    String[] values = s.split("\|");
    // validate values.length and set values trimming them first
}

如果只设置特定的字段,你最好写一个静态工厂方法(比如Person::createFromFileRow)。