Home » Core Java » Java 8 Read a File Line by Line Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java 8 Read a File Line by Line Example

Hello readers, in this tutorial, we will learn the Java8 Stream’s API for reading a file’s content line-by-line and we will explore its different characteristics.

1. Introduction

These days in the programming universe reading the file content is one of the most habitual files manipulation task in Java. In the ancient Java world, the code to read the text file line-by-line was very tedious. In Java8, JDK developers have added new methods to the java.nio.file.Files class which has opened new gateways for the developers and these new methods offer an efficient reading of the files using the Streams.

 
Java8 has added the Files.lines() method to read the file data using the Stream. The attractiveness of this method is that it read all lines from a file as a Stream of strings. This method,

  • Reads the file data only after a Terminal operation (such as forEach(), count() etc.) is executed on the Stream
  • Reads the file content line-by-line by using the Streams
  • Works by reading the Byte from a file and then decodes it into a Character using the UTF-8 character encoding

Do remember, Files.lines() is different from the Files.readAllLines() as the latter one reads all the lines of a file into a list of String elements. This is not an efficient way as the complete file is stored as a List resulting in an extra memory consumption.

Java8 also provides another method i.e. Files.newBufferedReader() which returns a BufferedReader to read the content from the file. Since both Files.lines() and Files.newBufferedReader() methods return Stream, developers can use this output to carry out some extra processing.

Now, open up the Eclipse Ide and we will go over these methods to read a file line-by-line using the Java8 Lambda Stream.

2. Java8 Read a File Line by Line Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure if you’re confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project

Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details

Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters

Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Java8ReadFile</groupId>
	<artifactId>Java8ReadFile</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation

Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)

Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to show the Files.lines() and Files.newBufferedReader() methods usage. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation

Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: ReadFileLineByLineDemo. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (ReadFileLineByLineDemo.java)

Fig. 8: Java Class (ReadFileLineByLineDemo.java)

3.1.1 Example of Reading File in Java8

Here is the complete Java program to read an input file line-by-line using the Lambda Stream in Java8 programming.

ReadFileLineByLineDemo.java

package com.jcg.java;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

/* 
 * A simple program that reads a text file line-by-line using Java8.
 * @author Batra, Yatin
 */
public class ReadFileLineByLineDemo {

	public static void main(String[] args) {
		String fName = "config/days.txt";

		// Method #1 - Read all lines as a Stream
		fileStreamUsingFiles(fName);

		System.out.println();

		// Method #2 - Read file with a filter
		filterFileData(fName);

		System.out.println();

		// Method #3 - In Java8, 'BufferedReader' has the 'lines()' method which returns the file content as a Stream
		fileStreamUsingBufferedReader(fName);
	}

	// Method #1
	private static void fileStreamUsingFiles(String fileName) {
		try {
			Stream<String> lines = Files.lines(Paths.get(fileName));
			System.out.println("<!-----Read all lines as a Stream-----!>");
			lines.forEach(System.out :: println);
			lines.close();
		} catch(IOException io) {
			io.printStackTrace();
		}
	}

	// Method #2
	private static void filterFileData(String fileName) {
		try {
			Stream<String> lines = Files.lines(Paths.get(fileName)).filter(line -> line.startsWith("s"));
			System.out.println("<!-----Filtering the file data using Java8 filtering-----!>");
			lines.forEach(System.out :: println);
			lines.close();
		} catch(IOException io) {
			io.printStackTrace();
		}
	}

	// Method #3
	private static void fileStreamUsingBufferedReader(String fileName) {
		try {
			BufferedReader br = Files.newBufferedReader(Paths.get(fileName));
			Stream <String> lines = br.lines().map(str -> str.toUpperCase());
			System.out.println("<!-----Read all lines by using BufferedReader-----!>");
			lines.forEach(System.out::println);
			lines.close();
		} catch (IOException io) {
			io.printStackTrace();
		}
	}
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application

Fig. 9: Run Application

5. Project Demo

The above code shows the following logs as output.

# Logs for 'ReadFileLineByLineDemo' #
=====================================
<!-----Read all lines as a Stream-----!>
sunday
monday
tuesday
wednesday
thursday
friday
saturday

<!-----Filtering the file data using Java8 filtering-----!>
sunday
saturday

<!-----Read all lines by using BufferedReader-----!>
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at the Java8 Files.lines() and Files.newBufferedReader() methods for reading a file line-by-line.

7. Download the Eclipse Project

This was an example of reading files in Java8.

Download
You can download the full source code of this example here: Java8ReadFile
(No Ratings Yet)
2 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Yatin BatraTobias Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Tobias
Guest
Tobias

Hey,
thanks for this example!
As far as I know,the Stream returned by Files.lines should be closed after usage. Preferably this should be done with a try-with-resources statement.

try (Stream files = Files.list(Paths.get(destination))){
files.forEach(path -> {
// Do stuff
});
}

Best regards