Core Java

Java Read File Line by Line Example

Photo of YatinYatinFebruary 5th, 2018Last Updated: July 20th, 2020
2 288 6 minutes read

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 8Stream’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 thejava.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 theFiles.lines() method toread 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 aTerminal operation (such asforEach(),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 theUTF-8 character encoding

Do remember,Files.lines() is different from theFiles.readAllLines() as the latter one reads all the lines of a file into a list of String elements. This isnot 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 aBufferedReader to read the content from the file. Since bothFiles.lines() andFiles.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 toFile -> 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 apom.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 thesrc/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 theFiles.lines() andFiles.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 intoJava8 Stream and printing it line by line
  • Approach 2: This approach (i.e.filterFileData(……)) talks about reading a file intoJava8 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 asBufferedReader.lines(……) that lets theBufferedReader returns the content asStream

Important points:

  • In the above approaches, we have omitted thetry-with-resources concept for simplicity and mainly focused on the new ways of reading the file. However, just for developers curiositytry-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 theBufferedReader andScanner 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
packagecom.jcg.java;
 
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.nio.file.Files;
importjava.nio.file.Paths;
importjava.util.stream.Stream;
 
/*
 * A simple program that reads a text file line-by-line using Java8.
 * @author Batra, Yatin
 */
publicclassReadFileLineByLineDemo {
 
    publicstaticvoidmain(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
    privatestaticvoidfileStreamUsingFiles(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
    privatestaticvoidfilterFileData(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
    privatestaticvoidfileStreamUsingBufferedReader(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!

Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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 8Files.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 8Files.newBufferedReader() method in order to read a file line by line. This method returns the contents as aStream
  • 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

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinFebruary 5th, 2018Last Updated: July 20th, 2020
2 288 6 minutes read
Photo of Yatin

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).

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.