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

readLine: Reading Text Line by Line

Use readLine() to efficiently read entire lines from a file, returning null at end-of-stream.

readLine: Reading Text Line by Line

What you'll learn: How to use readLine() to efficiently read entire lines of text from a file in one method call.


The Core Idea

Until now, you've been reading characters one at a time or in chunks using read() methods. But text files are naturally organized into lines—sequences of characters ending with a newline. BufferedReader offers a powerful method called readLine() that reads an entire line at once, stripping off the line terminator, and returns it as a String.

Think of it like reading a book: you could spell out each letter individually (character-by-character reading), or you could read whole sentences at a time (line-by-line reading). The latter is far more natural and efficient for processing text.

How readLine() Works

When you call readLine() on a BufferedReader, it:

  1. Reads characters until it encounters a line terminator (\n, \r, or \r\n)
  2. Returns all the characters before the terminator as a String (the terminator itself is consumed but not included)
  3. Returns null when the end of the stream is reached

This null return is your signal that there's no more data—perfect for loop conditions.

Using readLine()

BufferedReader reader = new BufferedReader(new FileReader("data.txt"));

String line = reader.readLine();  // Read first line
while (line != null) {            // Continue until end-of-stream
    System.out.println(line);     // Process the line
    line = reader.readLine();     // Read next line
}

reader.close();

Notice you check for null, not an empty string—an empty string means a blank line exists in the file, while null means you've reached the end.

Key Takeaway: readLine() efficiently reads entire lines as strings, returning null at end-of-stream, making it the standard way to process text files line by line.