import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;java
/**
* Java8 新API讀取文件內容
*
* Created by wangyingjie1 on 2017/2/22.
*/
public class ReadFile {函數
public static void main(String[] args) {get
try {string
String fileName = "D:\\SrcCode\\Java8InAction\\src\\main\\resources\\lambdasinaction\\chap5\\data.txt";it
//讀取文件
Stream<String> stringStream = Files
.lines(Paths.get(fileName), Charset.defaultCharset())
.flatMap(line -> Arrays.stream(line.split(" ")));io
List<String> words = stringStream.collect(Collectors.toList());
System.out.println("words===>" + words);class
List<String> lineLists = Files
.lines(Paths.get(fileName), Charset.defaultCharset())
.flatMap(line -> Arrays.stream(line.split("\n")))
.collect(Collectors.toList());import
//輸出文件函數
System.out.println("lineLists====" + lineLists.size());stream
//輸出每一行文件內容
lineLists.stream().forEach(System.out::println);lambda
//統計單詞的個數
long uniqueWords = Files.lines(Paths.get(fileName), Charset.defaultCharset())
.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct()
.count();
System.out.println("There are " + uniqueWords + " unique words in data.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}