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.



















Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap