2017-01-24 55 views
1

我要讀包含文件people.txt:如何分割一行文件內容行,保存到列表

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

我想拆分此文件的內容,並將其保存到列表人(List<Person>),其中只有名稱和性別字段必須設置。

class Person { 
    String name; 
    String sex; 
} 

如何使用Java 8實現這一目標?

回答

3

假設每個人在新的一行:

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)。

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

我沒有編譯過這個,但應該做這個工作。

+2

我想你可能需要'line.split(「\\ s * \\ | \\ s *」)''。 '|'需要轉義,最好包含空格。 – msandiford

+0

'map(array - > new Person(array [0],array [2]))'是一個硬編碼解決方案,只是在這種情況下看起來很簡潔,沒有任何檢查和附加邏輯 – Andrew