Reading Files Line-by-Line with BufferedReader
You'll learn the standard idiom for reading entire text files line-by-line using BufferedReader in a loop.
Now that you know readLine() returns lines without their terminators, it's time to master the most common pattern for processing text files: reading every line until there are no more lines to read.
The Core Pattern
readLine() returns null when the end of the file is reached. This makes it perfect for a loop condition:
BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = reader.readLine()) != null) {
// Process each line
System.out.println(line);
}
reader.close();
How It Works
Think of readLine() as a cursor moving down the file. Each call:
- Reads the next line of text
- Returns that line as a
String(without the line terminator) - Moves the cursor to the beginning of the next line
- Returns
nullwhen no more lines exist
The while loop continues until null signals "end of file."
Complete Example
try (BufferedReader reader = new BufferedReader(new FileReader("report.txt"))) {
String line;
int lineNumber = 1;
while ((line = reader.readLine()) != null) {
System.out.println(lineNumber + ": " + line);
lineNumber++;
}
}
This reads every line, prints it with a line number, and automatically closes the file when done.
The Assignment-in-Condition Idiom
Notice (line = reader.readLine()) inside the while condition? This assigns the result to line and tests if it's null simultaneously—a compact, idiomatic way to process streams until exhaustion.
Key Takeaway: The standard pattern for reading text files is a while loop with readLine() != null, which processes each line until the end of the file is reached.