Course contentsShow
← Java
Lesson 2010 of 2,87040. File I/O: Character StreamsFree lesson

Detecting End-of-File with readLine

Learn why readLine() returns null at EOF and how to use this to terminate reading loops correctly.

Detecting End-of-File with readLine

You'll learn how readLine() signals the end of a file and how to use this behavior to stop reading loops safely.

Why readLine() Returns null at EOF

When you're reading a text file line by line using BufferedReader's readLine() method, you eventually reach the end. Unlike byte streams where read() returns -1 to signal EOF, readLine() returns null when there are no more lines to read.

Think of it like reading pages in a book: when you flip past the last page, there's simply nothing there—not an empty page, but the absence of a page altogether. That's null.

Using null to Terminate Reading Loops

The most common pattern for reading entire files is to loop until readLine() returns null:

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // Process the line
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

Notice the condition != null—this is your loop terminator. Each iteration reads a line and checks if it's null. Once null is returned, the loop exits naturally.

Why This Pattern Matters

Without checking for null, your code would throw a NullPointerException when you try to use the returned value. The loop condition protects you by stopping exactly when the file ends, ensuring you process every line without errors.

Key Takeaway: readLine() returns null at end-of-file, not an empty string or -1. Always test for null in your loop condition to terminate reading correctly and avoid attempting to process non-existent lines.