Core Java

Java Read File Line by Line Example

Hello readers, in this tutorial, we will see an example of how to Read a File Line by Line in Java 8. We will learn the Java 8 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 file manipulation tasks 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 reads 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 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. Java 8 Read 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!

Java Read File Line by Line - 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.

Java Read File Line by Line - Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select the 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 the next button to proceed.

Java Read File Line by Line - 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.

Java Read File Line by Line - 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

1
2
3
4
5
6
7
    <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 us 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.

Java Read File Line by Line - 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.

Java Read File Line by Line - 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.

Java Read File Line by Line - 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.

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. In this tutorial we will talk about the 3 different approaches for reading a file:

  • Approach 1: This approach (i.e. fileStreamUsingFiles(……) talks about reading a file into Java8 Stream and printing it line by line
  • Approach 2: This approach (i.e. filterFileData(……)) talks about reading a file into Java8 Stream (like the one we’ll be using in Approach 1) but also apply a filter to it (i.e. Read only those elements from the file that start with an alphabet (s) and print it onto the console). This approach gives an edge to apply criteria while reading the file
  • Approach 3: This approach (i.e. fileStreamUsingBufferedReader(……) talks about a new Java8 method known as BufferedReader.lines(……) that lets the BufferedReader returns the content as Stream

Important points:

  • In the above approaches, we have omitted the try-with-resources concept for simplicity and mainly focused on the new ways of reading the file. However, just for developers curiosity try-with-resources is a concept that ensures that each resource is closed at the end of the statement execution
  • With enhancements in Java and introduction to Stream in Java8, developers have stopped using the BufferedReader and Scanner classes to read a file line by line as it does not offer the facilities like the ones offered by Java8 Streams API

Let us move ahead and understand the 3 different approaches with a practical example.

ReadFileLineByLineDemo.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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!

Run Application
Fig. 9: Run Application

5. Project Demo

The above code shows the following logs as output.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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 is all for this post. Happy Learning!

6. Java Read File Line by Line – Summary

In this tutorial, we had an in-depth look at:

  • Java 8 Files.lines() method in order to read a file line by line lazily and using the Stream API terminal operation (forEach(……)) to print lines from the file
  • Java 8 Files.newBufferedReader() method in order to read a file line by line. This method returns the contents as a Stream
  • We also an introduction of Java 8 Stream API methods to make ourselves familiar with this new concept

7. Download the Eclipse Project

This was an example of how to Read a File Line by Line in Java 8.

Download
You can download the full source code of this example here: Java Read File Line by Line Example

Last updated on Apr. 27th, 2020

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Tobias
Tobias
6 years ago

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

Back to top button