Java 9 already in full swing and ready for feature complete by end of May. Even though Java 8 released couple of years back, I’m sure there are very few companies moved to even Java 8 JDK for their production environment. Few still uses JDK7 and JDK6.
Java 8 by default comes with lots of smart features which I believe we hardly looked at. Sometime back I’ve written an article on Java 8 Stream API Operations and Lambda Expression.
In this tutorial we will go over steps and how we can use Java 8 Stream package to read file content line by line. If you want to go over traditional approach
(pre Java 8) then follow this tutorial which uses FileReader
and BufferReader
utils.
Also, if you have below questions then you are at right place.
- Java 8 Stream of Lines – Read File Line by Line
- Java 8 API Stream by Example
- java – How to read from files with Files.lines(…) and forEach
- Java 8: Reading A File Into A String
- java 8 write stream to file
There are 5 total ways to convert whole text file to a String in Java.
- Files.lines()
- Files.newBufferedReader()
There are 3 more methods:
- Files.readString()
- Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
- FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8); – Apache Commons IO Dependency
Visit below tutorials for these 3 methods.
Let’s get started with 1st 2 methods in this program:
Step-1
Create class CrunchifyJava8StreamReadFile.java
Step-2
We are going to create read line utility using two below approaches. Create different methods for each utility.
lines()
andStream
ApproachnewBufferedReader
andStream
Approach
Step-3
collect
performs a mutable reduction operation
on the elements of this stream using a Collector
. Here is details.
I would suggest to go through it thoroughly.
Step-4
We will read file crunchify-java8-stream.txt
with below content. Copy the content and put it into your C drive or Mac’s Downloads folder.
Welcome to Crunchify's JDK 8 Stream API tutorial More than 500 Java and Spring MVC tutorials Company: Crunchify Address: NYC Contact: App Shah
Here is a complete Java Program:
- Create class CrunchifyJava8StreamReadFile.java
- Copy below code and add it to file.
package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Crunchify.com * How to Read a File line by line using Java 8 Stream - Files.lines() and Files.newBufferedReader() Utility APIs. */ public class CrunchifyJava8StreamReadFile { public static void main(String[] args) { String crunchifyFile = "/Users/app/Download/crunchify-java8-stream.txt"; // lines() and Stream Approach CrunchifyReadFile1(crunchifyFile); // newBufferedReader and Stream Approach CrunchifyReadFile2(crunchifyFile); } // Read file using lines() and Stream Approach private static void CrunchifyReadFile1(String crunchifyFile) { // Stream: A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream. Stream<String> crunchifyStream = null; try { // Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset crunchifyStream = Files.lines(Paths.get(crunchifyFile)); } catch (IOException e) { e.printStackTrace(); } log("============= Result from lines() and Stream Approach ============="); assert crunchifyStream != null; // forEach(): Performs an action for each element of this stream. // This is a terminal operation. crunchifyStream.forEach(System.out::println); } // Read file using newBufferedReader and Stream Approach private static void CrunchifyReadFile2(String crunchifyFile) { BufferedReader crunchifyBufferReader = null; try { // newBufferedReader: Opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner. // Bytes from the file are decoded into characters using the UTF-8 charset. // Paths: This class consists exclusively of static methods that return a Path by converting a path string or URI. crunchifyBufferReader = Files.newBufferedReader(Paths.get(crunchifyFile)); } catch (IOException e) { e.printStackTrace(); } // toList: returns a Collector that accumulates the input elements into a new List // lines(): returns a Stream, the elements of which are lines read from this BufferedReader List<String> crunchifyList = crunchifyBufferReader != null ? crunchifyBufferReader.lines().collect(Collectors.toList()) : null; log("\n============= Result from newBufferedReader and Stream Approach ============="); // forEach: performs the given action for each element of the Iterable until all elements have been processed or the // action throws an exception. assert crunchifyList != null; crunchifyList.forEach(System.out::println); } private static void log(String string) { System.out.println(string); } }
Result/Output:
Just run above program as a Java Application and you should see result like below.