Buffered Reader Example in Java
On this page (10sections)
Introduction
Buffered Reader is a classic Java console program that demonstrates the concept with complete source code and sample output. Java I/O reads and writes bytes and characters from files, streams and the console.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
BufferedReader is a wrapper for both “InputStreamReader/FileReader”, which buffers the information each time a native I/O is called. The buffer size may be specified, or the default size may be used. Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
Syntax
BufferedReader Variable_name = new BufferedReader("Directory_Of_The_File");
Buffered Reader Example Program
import java.io.*;
public class BufferedReaderDemo {
public static void main(String[] args) throws Exception {
String str = null
try{
BufferedReader buffread = new BufferedReader("c:/newfile.txt");// Assuming a text file newfile.txt containing data "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
while ((str = buffread.readLine()) != null) {
System.out.println(str);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Sample Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
When to use
Use this buffered reader example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.io.*;imports a class used later in the program. -
String str = nullupdates a variable used in the calculation or output. -
BufferedReader buffread = new BufferedReader("c:/newfile.txt");// Assuming a text file newfile.txt containing data "ABCDEFGHIJKLMNOPQRSTUVWXYZ"updates a variable used in the calculation or output. -
while ((str = buffread.readLine()) != null) {updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Buffered Reader to confirm the program behaves correctly.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.