Java

How to read a file line by line in Java

Files can be huge in size containing hundreds and thousands of lines of information so instead of reading the entire file which will take system resources, we can print text files line by line using BufferedReader class in Java. So in this article, we will provide you with a thorough explanation along with a code that can be used to read your files. So, let’s get started

Reading files line-by-line using BufferedReader class in Java

To read any file you need to initialize a file handling process in Java which you can do by typing:

import java.io.*;

Next, we have imported a class that is used to read data from the keyboard when pressed by the user as shown below:

import java.util.Scanner;

After that, we have created a public class where all our coding will reside by typing:

public class FileReaderLineByLine {

……

}

This will be your main function within a class where we have passed the string argument:

public static void main(String[] args)

Now we are initializing a file with the name of ‘Employees.txt’ along with the path where it is located:

File f=new File("Employees.txt");

Now we have initialized a file reader variable ‘fr’ that will be used to fetch the content of the whole file and initially set the value to null:

FileReader fr=null;

After that, we have also initialized a buffered reader which will be used to read the fill line by line and set its value also to null:

BufferedReader br = null;

It is a compulsory step to implement the exception handling process here as sometimes it is possible that you are reading a file that is huge or in case of any error occurs then the program can be crashed which makes a file corrupt that you are trying to read. So to do that you need to implement the ‘try’ and ‘catch’ process. Inside the try body, you should read the file for security purposes as shown below:

try
   {
fr= new java.io.FileReader(f);
br=new BufferedReader(fr);
           while((line=br.readLine())!=null)
           {
System.out.println(line);
           }
br.close();
fr.close();
   }

It is really important to read files line by line because sometimes the file has a huge size and you can’t read the whole file as this will have a great impact on the performance of your system. Now next is the catch part which will execute only if any error occurs during the file reading process and its syntax is as follows.

catch (IOException ex) {
System.err.println("Error while reading file: "+ ex.getMessage());
   }

Now, this is where we will show you the whole code that we have explained in chunks in the previous part which is shown below:

import java.io.*;
import java.util.Scanner;
public class FileReaderLineByLine {
    public static void main(String[] args) {
System.out.println("Reading file line-by-line using BufferedReader object\n");
System.out.println("");
        File f=new File("Employees.txt");
FileReaderfr=null;
BufferedReaderbr = null;
        try
        {
            String line;
fr= new java.io.FileReader(f);
br=new BufferedReader(fr);
           while((line=br.readLine())!=null)
           {
System.out.println(line);
           }
br.close();
fr.close();
   }//try
    catch (IOException ex) {
System.err.println("Error while reading file: "+ ex.getMessage());
    } //catch
}//main()
}//class

If you want to execute this java code in the Linux operating system then you can do that by using any text editor of your choice. For example, we are using a nano text editor so we will do that by typing.

$ nano FileReaderLineByLine.java

The next step is to write the code and then save it:

Now to execute this code you need to first make sure that you have installed the java development kit (JDK) application in your Linux operating system by typing:

$ sudo apt install default-jdk

After that, you need to compile the code first before trying to execute the program.

$ javac FileReaderLineByLine.java

$ java FileReaderLineByLine

Now you can see that after executing the file it is reading data that is available in the text file of “Employees.txt” which is shown below:

Note: You need to open a terminal and then access the same directory where this text file is present otherwise you won’t be able to read this file.

Reading files line-by-line using Scanner class in Java

There is one more method to read files line by line is by using a Scanner class in java and for that, you need to type.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFileLineByLine {

    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File("Employees.txt"));
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

Conclusion

Sometimes Files can be huge in size containing hundreds and thousands of lines of information. Instead of reading the entire file which will take system resources, we can read them line by line using the BufferedReader class in Java. In this article, we have taught you how you can read any file using a Java programming language and for that, you need to import the file handling process. You also need to implement the try and catch process which is used to handle the file exceptions in case of any error while reading a file which has been discussed in this article.

About the author

Taimoor Mohsin