In this Java tutorial, you will learn how to read contents of a File line by line using BufferedReader class, with examples.

Read contents of a file line by line using BufferedReader

Following are the steps to read contents of a File line by line using BufferedReader:

Step 1: Load the file into buffer of BufferedReader.

BufferedReader br = new BufferedReader(new FileReader(filename));

BufferedReader provides an efficient way of reading characters, lines and arrays, from a character stream.

Step 2: Use java.io.BufferedReader.readLine() method to get a line and iterative calls to the method brings us the subsequent lines.

line = br.readLine();

If stream from the specified file contains characters, readLine() returns characters till the encounter of new line or line feed. And if the stream is empty, i.e., no more characters left in the stream, the method returns null, which is an indication that whole contents of file have been read.

Examples

ADVERTISEMENT

1. Read File Line by Line using BufferedReader

In this example, we have a text file named samplefile.txt, and we will read contents of this file, line by line, using BufferedReader class.

samplefile.txt

This is first line.
 This is second line.
 This is third line.
 Welcome to www.tutorialkart.com.

Example.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Read contents of a File line by line using BufferedReader
 * www.tutorialkart.com
 */
public class Example {
 
    public static void main(String args[]){
    	String filename = "samplefile.txt";
        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(new FileReader(filename));
            System.out.println("---------Contents of the file---------\n-------------------------------------\n");
            while( (line = br.readLine()) != null){
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
        	System.err.println("Oops! Please check for the presence of file in the path specified.");
            e.printStackTrace();
        } catch (IOException e) {
        	System.err.println("Oops! Unable to read the file.");
        	e.printStackTrace();
        }
    }
}

When the above program is run, output to the console is as shown in the following.

Output

---------Contents of the file---------
-------------------------------------

This is first line.
This is second line.
This is third line.
Welcome to www.tutorialkart.com.

Note : Provide the path to the file correctly. In this example, the file is placed at the root of Project Folder (of Eclipse Project).

Conclusion

In this Java Tutorial, we have seen how to use java.io.BufferedReader and its methodjava.io.BufferedReader.readLine() to read the contents of a file line by line.