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,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- Install Python on Alpine Linux - Docker - Docker
- How to install AWS CLI on Ubuntu - AWS
- Fix - Website Connection timed out Error Code 522 (Cloudflare) - HowTos
- Todays Apple Spring Loaded Event Live Updates - Apple
- Android : Execute some code after back button is pressed - Android
- How to Export a PowerShell Script/Cmdlet Output to a Text File - Powershell
- SCP Copy all files from directory to Local Folder - Linux
- Converting Array into ArrayList - Java - Java