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.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Code2care.org 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";
        Files.lines(Paths.get(filePath)).forEach(System.out::println);

    }
}
Output:

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 java.util.stream.Stream<String> object.

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.