01 / 20

BufferedReader
for Files

Learn to read text files line by line using Java's BufferedReader: efficient, clean, and essential for real-world applications.

Java

What is File I/O?

Programs often need to read data from files or write data to files. This is called File I/O (Input/Output). Think of it as opening a book, reading its pages, and closing it when you are done.

data.txt File on Disk read Buffered Reader lines Your Program

Why BufferedReader?

★ Efficient
Reads chunks of data into an internal buffer, reducing the number of disk reads.
★ Line-Based
The readLine() method returns one complete line at a time: perfect for text files.
★ Flexible
Wraps any Reader object, so it works with files, network streams, and more.

The Wrapper Pattern

BufferedReader does not read files by itself. It wraps a FileReader, which handles the actual file access. This layered design is called the Decorator Pattern.

BufferedReader FileReader "data.txt"

The Core Pattern

Java
BufferedReader br = new BufferedReader(
    new FileReader("data.txt")
);

String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

br.close();

Anatomy of the Read Loop

1
Assign and test: line = br.readLine() reads the next line and stores it in line.
2
Check for null: If readLine() returns null, we have reached the end of the file.
3
Process the line: Inside the loop body, do whatever you need: print it, parse it, store it.
4
Repeat: The loop goes back to step 1, reading the next line automatically.

FileReader vs BufferedReader

FileReader BufferedReader
Reads One character at a time Chunks into a buffer
Has readLine()? ✕ No ✓ Yes
Performance Slower (many disk hits) Faster (fewer disk hits)
Use Alone? Rarely useful alone Wraps FileReader

Handling Exceptions

File operations can fail: the file might not exist, or you might lack permission. Java forces you to handle these checked exceptions using try-catch or throws.

Java
try {
    BufferedReader br = new BufferedReader(
        new FileReader("data.txt")
    );
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    br.close();
} catch (IOException e) {
    System.out.println("Error: " + e.getMessage());
}

Try-With-Resources

Java 7 introduced try-with-resources, which automatically closes the reader when the block exits: even if an exception is thrown. This is the modern, preferred approach.

Java
try (BufferedReader br = new BufferedReader(
        new FileReader("data.txt"))) {

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
// br.close() is called automatically!
} catch (IOException e) {
    e.printStackTrace();
}

How to Apply It

1
Import: Add import java.io.*; at the top of your file.
2
Create: Wrap FileReader inside BufferedReader inside try(...).
3
Loop: Use the while ((line = br.readLine()) != null) idiom to read all lines.
4
Process: Inside the loop, parse, store, or print each line.
5
Handle errors: Catch IOException and provide a meaningful message.

Example 1: Print All Lines

Given a file poem.txt, print every line to the console.

Java
import java.io.*;

public class PrintPoem {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(
                new FileReader("poem.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("Could not read file.");
        }
    }
}

Example 2: Count Lines

Count the total number of lines in a file called log.txt.

Java
import java.io.*;

public class LineCounter {
    public static void main(String[] args) {
        int count = 0;
        try (BufferedReader br = new BufferedReader(
                new FileReader("log.txt"))) {
            while (br.readLine() != null) {
                count++;
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
        System.out.println("Lines: " + count);
    }
}

Example 3: Search a File

Print every line from notes.txt that contains the word "ERROR".

Java
import java.io.*;

public class ErrorFinder {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(
                new FileReader("notes.txt"))) {
            String line;
            int lineNum = 0;
            while ((line = br.readLine()) != null) {
                lineNum++;
                if (line.contains("ERROR")) {
                    System.out.println(
                        "Line " + lineNum + ": " + line);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Common Mistakes

✕ Forgetting to Close
Not calling close() or not using try-with-resources can leak file handles and crash your program over time.
✕ Missing Parentheses
Writing line = br.readLine() != null without the outer parentheses assigns a boolean, not a String.
✕ Ignoring IOException
The code will not compile if you do not catch or declare IOException. It is a checked exception.

Summary Table

Concept Details
Import import java.io.*;
Create new BufferedReader(new FileReader(path))
Read Loop while ((line = br.readLine()) != null)
End of File readLine() returns null
Close Use try-with-resources (automatic)
Exception Catch IOException

Question 1 of 5

What does readLine() return when there are no more lines to read?

Question 2 of 5

Which class does BufferedReader need to wrap in order to read from a file?

Question 3 of 5

What is the main advantage of try-with-resources over a manual try-catch with br.close()?

Question 4 of 5

What is wrong with the line above?

Question 5 of 5

If scores.txt contains the lines "10", "25", and "5", what is the output?