Java 8 – Stream of lines
在下面的实例中,将使用Stream来一行一行的读取文件
将要读取的文件 data.txt 内容如下:
Lokesh
Gupta
Never
store
password
except
in mind.
将上面的文件一行一行的读取,如果有一行包含 password ,将这行打印出来
1. Read file line by line – Java 8 Stream
利用Java 8 Stream读取文件内容,过滤包含 password 的行,并取出第一条打印出来
private static void readStreamOfLinesUsingFiles() throws IOException
{
Stream<String> lines = Files.lines(Paths.get("c:/temp", "data.txt"));
Optional<String> hasPassword = lines.filter(s -> s.contains("password")).findFirst();
if(hasPassword.isPresent())
{
System.out.println(hasPassword.get());
}
//Close the stream and it's underlying file as well
lines.close();
}
2. Read file line by line – FileReader
直到java7,可采用下面的方式来读取文件,实现方法有很多,但不是本文的重点,只是与上面的例子对比来看
private static void readLinesUsingFileReader() throws IOException
{
File file = new File("c:/temp/data.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null)
{
if(line.contains("password")){
System.out.println(line);
}
}
br.close();
fr.close();
}
3. Read file as stream of lines – try-with-resources
第一个例子已经能够满足我们在应用程序中逐行读取文件的需要了, 但如果你还想让它变得更好, 那么我们可以使用 try-with-resources 的方式, 这样会省去最后关闭流 close() 的操作。
private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
Path path = Paths.get("c:/temp", "data.txt");
//The stream hence file will also be closed here
try(Stream<String> lines = Files.lines(path))
{
Optional<String> hasPassword = lines.filter(s -> s.contains("password")).findFirst();
if(hasPassword.isPresent()){
System.out.println(hasPassword.get());
}
}
}
当一个Stream产生另外一个Stream的时候,close 方法会链式调用(它下面的Stream也会调用),可以采用下面的方法编写:
private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
Path path = Paths.get("c:/temp", "data.txt");
//When filteredLines is closed, it closes underlying stream as well as underlying file.
try(Stream<String> filteredLines = Files.lines(path).filter(s -> s.contains("password")))
{
Optional<String> hasPassword = filteredLines.findFirst();
if(hasPassword.isPresent()){
System.out.println(hasPassword.get());
}
}
}
你想测试一下它下面的Stream的有没有触发 close ,可以用 onClose 来测试一下
private static void readStreamOfLinesUsingFilesWithTryBlock() throws IOException
{
Path path = Paths.get("c:/temp", "data.txt");
//When filteredLines is closed, it closes underlying stream as well as underlying file.
try(Stream<String> filteredLines = Files.lines(path)
//test if file is closed or not
.onClose(() -> System.out.println("File closed"))
.filter(s -> s.contains("password"))){
Optional<String> hasPassword = filteredLines.findFirst();
if(hasPassword.isPresent()){
System.out.println(hasPassword.get());
}
}
}
输出
password
File closed
翻译自:https://howtodoinjava.com/java8/read-file-line-by-line-in-java-8-streams-of-lines-example/