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.
More Posts related to Java,
- How to install Java 11 on Mac
- Get Client IP address from HTTP Response in Java
- SharePoint Open in the client application document opens in browser
- How to verify if java is installed on the computer and get version detail
- Java - Check if array contains the value
- Your JBoss Application Server 7 is running However you have not yet added any users to be able to access the admin console
- How to run Java Unit Test cases with Apache Maven?
- What Java version is used for Minecraft 1.18
- List of jar files for Jax-ws (SOAP) based Java Web Services
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- Convert Instant timestamp into LocalDateTime Java Code Example
- Java - Calculate time taken for the code to execute in milliseconds or nanoseconds
- Create simple struts2 project using maven commands
- Java - PatternSyntaxException
- List of Online Java compiler with console
- Minecraft Java Edition
- How to declare and initialize Array in Java Programming
- [Solved] com.sun.xml.ws.transport.http.servlet.WSServletContextListener ClassNotFoundException
- Java XML-RPC 3.1.x based web service example
- Simple Struts 2 Tutorial in eclipse with tomcat 7 server
- Java 8 foreach loop code examples
- Java -Day of the week using Java 8 DayOfWeek Enum
- Java 8 - Convert List to Map Examples
- Java: TimeZone List with GMT/UTC Offset
- list of jars required for hibernate 4.x.x
More Posts:
- XmlRpcException ConnectException connection refused error - Java
- Free and easy audio video screen recording using Microsoft PowerPoint - Microsoft
- Android appcompat_v7 Error retrieving parent for item: No resource found that matches the given name - Android
- Todays Apple Spring Loaded Event Live Updates - Apple
- JavaScript : Get url protocol HTTP, HTTPS, FILE or FTP - JavaScript
- [Fix] Java Exception with Lambda - Cannot invoke because object is null - Java
- How to Change Text Size for Android ActionBar - Android
- Android Toolbar example with appcompat_v7 21 - Android