Java BufferedReader and FileReader example read text file

Using Java BufferedReader and FileReader to open a text file and read the contents of it :

In this example, I will show you one basic Java File I/O operation : “Reading the contents” of a text file. We will use ‘BufferedReader’ and ‘FileReader’ class in this example. What these classes are used to do mainly ? Let’s check :

BufferedReader :

BufferedReader is used to read text from a input stream. It buffers the input reading for more efficiency. Without buffering , reading operations will become more time consuming.

FileReader :

FileReader is used mainly for reading character file. We will use one ‘FileReader’ wrapped with a ‘BufferedReader’. The read() operation of ‘FileReader’ is costly. So if we wrap it with ‘BufferedReader’ , it will buffer the inputs and make the process more smoother.

Let’s take a look into the Java Program :

Java Program to read contents of a text file :

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    /**
     * Utility function to print
     */
    static void print(String string) {
        System.out.print(string);
    }


    public static void main(String[] args) {
        ArrayList readingLines = new ArrayList<>(); //1
        String line;
        try {
            FileReader fileReader = new FileReader("in.txt"); //2

            BufferedReader bufferedReader = new BufferedReader(fileReader); //3
            while ((line = bufferedReader.readLine()) != null) {
                readingLines.add(line); //4
            }

            bufferedReader.close();

            for (int i = 0; i < readingLines.size(); i++) {
                print(readingLines.get(i));
            }

        } catch (Exception e) {

        }
    }
}

How this program works :
1. First create one ‘ArrayList‘ of ‘String‘ to store the contents of the file.
2. Create one ‘FileReader‘ object by passing the file location to its constructor.
3. Wrapped this ‘FileReader‘ object with a ‘BufferedReader‘.
4. Now use one while loop, to read lines from the file. And store it in a variable ‘line‘.
5. After ‘while‘ loop is completed , close the BufferedReader.
6. Finally, to print the contents, simply use one ‘for’ loop to print out the contents of the ArrayList ‘readingLines‘.

Leave a Reply