Java 8 Read File Line By Line

Java 8 has addded Files.readAllLines() method ,which can be used to read file as List of Strings.

Read file as a List of Strings

1
2
3
4
5
6
7
8
9
10
11

public class Java8ReadFileAsListOfStrings {

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

}

Text file 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