BufferedReader
for Files
Learn to read text files line by line using Java's BufferedReader: efficient, clean, and essential for real-world applications.
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.
Why BufferedReader?
readLine() method returns one complete line at a time: perfect for text files.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.
The Core Pattern
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
line = br.readLine() reads the next line and stores it in line.readLine() returns null, we have reached the end of the file.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.
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.
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
import java.io.*; at the top of your file.FileReader inside BufferedReader inside try(...).while ((line = br.readLine()) != null) idiom to read all lines.IOException and provide a meaningful message.Example 1: Print All Lines
Given a file poem.txt, print every line to the console.
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.
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".
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
close() or not using try-with-resources can leak file handles and crash your program over time.line = br.readLine() != null without the outer parentheses assigns a boolean, not a String.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?
null at the end of the file. An empty string "" represents a blank line, which is different from end-of-file. The value -1 is returned by the lower-level read() method, not readLine().Question 2 of 5
Which class does BufferedReader need to wrap in order to read from a file?
readLine() method. Scanner is a different approach to reading input. PrintWriter is for writing, not reading.Question 3 of 5
What is the main advantage of try-with-resources over a manual try-catch with br.close()?
IOException. It does not affect performance or file type support.Question 4 of 5
Consider this code fragment:
String line = br.readLine() != null;
The programmer intended to read a line and check whether the file has ended.
What is wrong with the line above?
br.readLine() != null first, which produces a boolean. Then it tries to assign that boolean to a String, which will not compile. The correct form is (line = br.readLine()) != null with extra parentheses.Question 5 of 5
BufferedReader br = new BufferedReader(
new FileReader("scores.txt"));
String line;
while ((line = br.readLine()) != null) {
int score = Integer.parseInt(line);
System.out.println(score * 2);
}
If scores.txt contains the lines "10", "25", and "5", what is the output?
int using Integer.parseInt(), multiplied by 2, and printed. So the output is 20, then 50, then 10, each on a separate line.