In this tutorial, we will take a look at how to read a 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.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!