Java 8 Read File As A Stream

Java 8 has added Files.lines() method, which can be used to read the file as Stream.

Read file as a stream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Java8ReadFileAsStream {

public static void main(String[] args) throws IOException {
String filePath = "C:\\data\\demo\\sample.txt";
Stream<String> lines = Files.lines(Paths.get((filePath)));
lines.forEach(System.out::println);
}

}


sample.txt for testing.
1
2
3
4
5
6
7
public final class Files extends Object
This class consists exclusively of static methods that operate on files, directories, or other types of files.
In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations.

Since:
1.7

Output:

Share Comments