Read a File in Java using BufferedReader

In Java, one of the most widely-used classes for reading files is BufferedReader. The primary advantage of using BufferedReader is that it reads text from a character-input stream, buffering characters to provide efficient reading of characters, arrays, and lines. In this post, we'll explore how to use the BufferedReader class to read a file. 

1. Introduction to BufferedReader 

BufferedReader belongs to the java.io package. By buffering the reads, it minimizes native IO operations which can be more time-consuming. Its most commonly used method, readLine(), allows reading an entire line from the file at once. 

2. Reading a File Using BufferedReader 

Here's a basic example of reading a file using BufferedReader:

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

public class BufferedReaderDemo {
    public static void main(String[] args) {
        String filePath = "sample.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());
        }
    }
}

In this example: 

We wrap the FileReader with a BufferedReader. This allows us to read the file line by line. 

The readLine() method reads a line of text. When it reaches the end of the file, it returns null.

Using a try-with-resources statement ensures that the BufferedReader instance is closed automatically when it's no longer needed.

3. Reading a File Character by Character using BufferedReader 

1. Using the read() Method: 

The read() method of the BufferedReader class reads a single character from the file as an integer. We can cast this integer back to a char to get the actual character. Here's an example:

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

public class ReadCharacterByCharacterUsingArray {
    public static void main(String[] args) {
        String filePath = "sample.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            char[] charArray = new char[1]; // Array of size 1 to read one character at a time
            while (br.read(charArray, 0, 1) != -1) {
                System.out.print(charArray[0]);
            }
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());
        }
    }
}

2. Using the read(char[] cbuf, int off, int len) Method: 

The read(char[] cbuf, int off, int len) method reads characters into a portion of an array. Here's how you can use it to read a file character by character:

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

public class ReadCharacterByCharacterUsingArray {
    public static void main(String[] args) {
        String filePath = "sample.txt";

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            char[] charArray = new char[1]; // Array of size 1 to read one character at a time
            while (br.read(charArray, 0, 1) != -1) {
                System.out.print(charArray[0]);
            }
        } catch (IOException e) {
            System.out.println("Error reading the file: " + e.getMessage());
        }
    }
}

Both methods demonstrate how to read a file character by character using the BufferedReader class in Java.

4. Why Use BufferedReader? 

Efficiency: By using internal buffering, BufferedReader can read large chunks of data at once from the underlying source (like a file), making it more efficient compared to reading one character at a time. 

Convenience: The readLine() method provides an easy way to read an entire line without dealing with byte-to-character conversions or handling raw character arrays. 

5. Points to Remember 

While BufferedReader is efficient for reading text files, if you need to read binary files, consider using classes like FileInputStream or BufferedInputStream. 

Always close the BufferedReader once you're done to free up system resources. If you're using Java 7 or later, you can use the try-with-resources statement as shown above, which will automatically handle this for you. 

Comments