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



#Android #Java #Linux #Microsoft #Google #Python #MacOS #Notepad++ #Microsoft Teams #CSS #PHP #SharePoint #Html #Linux #C-Program #Bootstrap #jQuery #Sublime #Android-Studio #Facebook #Eclipse #WhatsApp #News #MySQL #Json #HowTos #JavaScript #FTP #S3


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 Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency