Read a file using Java 8 Stream

In this tutorial, we will take a look at how to read a file using Java 8 Stream.

Read file using Java 8 Stream

The most efficient and quickest way to read a print the contents of a file in Java 8 is by making use of the Steams API and Files class from java.nio package.

Code Example:
import java.nio.file.Files;
import java.nio.file.Paths;

 * Java Examples
 * Read and print out file lines
 * Using Java 8 Stream and Files
 * from java.nio library
public class JavaFilesWithStreamExample {

    public static void main(String[] args) throws IOException {

        String filePath = "/Users/code2care/IdeaProjects/lambdas/src/sample-data.txt";


This is file line 1
This is file line 2
This is file line 3

You may wonder where is the Stream here, well, Files.lines() method returns a<String> object.

Top Hashtags: