Java BufferedReader Class Declaration
The BufferedReader class in Java is part of the java.io package, which provides classes for system input and output through data streams, serialization, and the file system. To use BufferedReader, you first need to import it from the java.io package. Here’s how you declare a BufferedReader:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Additional code to read from the file
bufferedReader.close(); // Always close the stream
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, a BufferedReader is created by wrapping a FileReader that opens a file to be read. By buffering the characters, it significantly improves performance by reducing the number of reads directly from the file. The try-catch block ensures that any IOException is caught and handled gracefully.
Always Remember: When you're done using a BufferedReader, you should always close it to release any system resources associated with it. Failure to close the reader may lead to resource leaks in your program.
Java BufferedReader class constructors
The BufferedReader class provides many constructors that allow you to create instances of BufferedReader. These are the commonly used constructors:
1. `BufferedReader(Reader in)`: This constructor creates a BufferedReader that wraps around another Reader object, such as a FileReader or InputStreamReader. It uses the default buffer size of 8192 characters.
Example:
FileReader fileReader = new FileReader("file.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
2. `BufferedReader(Reader in, int size)`: This constructor is similar to the previous one but allows you to specify the buffer size. The `size` parameter determines the number of characters that can be buffered simultaneously.
Example:
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 4096);
In the above examples, we create instances of BufferedReader by wrapping them around a FileReader & an InputStreamReader, respectively. The FileReader reads characters from a file, while the InputStreamReader reads characters from an input stream, such as the console.
Java BufferedReader class methods
The BufferedReader class provides several methods that allow you to read data from the underlying character-based input stream. Let’s see some commonly used methods:
1. `read()`: This method reads a single character from the input stream & returns its integer representation. It returns -1 if the end of the stream is reached.
Example:
int character;
while ((character = bufferedReader.read()) != -1) {
System.out.print((char) character);
}
2. `read(char[] cbuf, int off, int len)`: This method reads characters from the input stream into a character array. It starts storing characters at the specified offset `off` & reads up to `len` characters. It returns the number of characters read or -1 if the end of the stream is reached.
Example:
char[] buffer = new char[1024];
int bytesRead;
while ((bytesRead = bufferedReader.read(buffer, 0, buffer.length)) != -1) {
System.out.print(new String(buffer, 0, bytesRead));
}
3. `readLine()`: This method reads a line of text from the input stream. It returns the line as a String, excluding the line termination characters (\r or \n). It returns null if the end of the stream is reached.
Example:
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
4. close (): This method closes the BufferedReader and releases any system resources associated with it. It's important to call this method when you're done reading from the BufferedReader to prevent resource leaks.
Example:
bufferedReader.close();
Java BufferedReader Example:
Let's discuss a simple example of using the BufferedReader class to read data from a file.
Suppose we have a file named "file.txt" with the following content:
Hello, World!
This is a sample file.
We will read its content using BufferedReader.
This is an example that reads the content of the file using BufferedReader:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("file.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

You can also try this code with Online Java Compiler
Run Code
In this example, we create a FileReader to read from the "file.txt" file. We then wrap the FileReader with a BufferedReader to enable buffered reading.
Inside the try block, we use a while loop to read lines of text from the file using the `readLine()` method. We continue reading until `readLine()` returns null, indicating the end of the file. Each line is printed to the console using `System.out.println()`.
After we finish reading, we close the BufferedReader using the `close()` method to release any system resources.
If any IOException occurs during the file reading process, it will be caught in the catch block, and the exception stack trace will be printed.
When you run this code, it will output the content of the "file.txt" file:
Hello, World!
This is a sample file.
We will read its content using BufferedReader.
This example shows how to use BufferedReader to read text from a file efficiently. Based on your requirements, you can modify the code to perform different operations, like processing the lines, storing them in a data structure, or writing them to another file.
Reading data from the console by InputStreamReader and BufferedReader
In addition to reading from files, BufferedReader can also be used to read input from the console. Let’s see an example that shows how to read user input from the console using InputStreamReader and BufferedReader:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ConsoleInputExample {
public static void main(String[] args) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
System.out.print("Enter your name: ");
String name = bufferedReader.readLine();
System.out.print("Enter your age: ");
String ageString = bufferedReader.readLine();
int age = Integer.parseInt(ageString);
System.out.println("Hello, " + name + "! You are " + age + " years old.");
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Enter your name: Ria
Enter your age: 23
Hello, Ria! You are 23 years old.
In this example, we create an InputStreamReader that reads from the standard input stream (System.in), representing the console. We then wrap the InputStreamReader with a BufferedReader to enable buffered reading from the console.
We prompt the user to enter their name using `System.out.print()`. Then, we use the `readLine()` method of BufferedReader to read the user's input as a string. The program waits for the user to enter a value and press the Enter key.
Next, we prompt the user to enter their age. Again, we use `readLine()` to read the user's input as a string. Since the age is expected to be an integer, we use `Integer.parseInt()` to convert the string to an integer.
Finally, we print a greeting message that includes the user's name and age.
After reading the input, we close the BufferedReader to release any system resources.
If any IOException occurs during the input reading process, it will be caught in the catch block, and the exception stack trace will be printed.
When you run this code, it will prompt you to enter your name and age, and then it will display a personalized greeting message based on the input provided.
Note: This example showcases how BufferedReader can be used in combination with InputStreamReader to read user input from the console interactively.
Another example of reading data from the console until the user writes stop:
Let’s discuss one more example that shows how to continuously read user input from the console using BufferedReader until the user enters the word "stop":
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ContinuousInputExample {
public static void main(String[] args) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String input;
while (true) {
System.out.print("Enter a message (or 'stop' to quit): ");
input = bufferedReader.readLine();
if (input.equalsIgnoreCase("stop")) {
break;
}
System.out.println("You entered: " + input);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

You can also try this code with Online Java Compiler
Run Code
Output
Enter a message (or 'stop' to quit): Hello
You entered: Hello
Enter a message (or 'stop' to quit): World
You entered: World
Enter a message (or 'stop' to quit): stop
In this example, we create an InputStreamReader & a BufferedReader in the same way as in the previous example.
We use a while loop to read user input from the console continuously. Inside the loop, we prompt the user to enter a message or type "stop" to quit the program.
We use the `readLine()` method to read the user's input as a string & store it in the `input` variable.
We then check if the user entered the word "stop" (case-insensitive) using the `equalsIgnoreCase()` method. If the user entered "stop", we use the `break` statement to exit the loop and terminate the program.
If the user enters any other message, we print it back to the console using `System.out.println()`.
The loop continues to prompt for input until the user enters "stop".
After the loop ends, we close the BufferedReader to release any system resources.
If any IOException occurs during the input reading process, it will be caught in the catch block, and the exception stack trace will be printed.
When you run this code, it will repeatedly prompt you to enter a message. It will display back each message you enter until you type "stop" to quit the program.
Note: This example shows how BufferedReader can be used to read user input continuously from the console until a specific condition is met, like the user entering a particular word or phrase to indicate the end of input.
Advantages of BufferedReader in Java
- Fast and Efficient
BufferedReader uses an internal buffer to read large blocks of characters at once, reducing disk access and improving performance. This makes it ideal for reading big files or input streams efficiently.
- Suitable for Large Input
It handles large files or continuous streams much better than classes like Scanner. BufferedReader reads data quickly without consuming too much memory, making it perfect for server logs, file processing, and batch input.
Disadvantages of BufferedReader in Java
- Requires Exception Handling
BufferedReader throws checked exceptions like IOException, so developers must handle them using try-catch blocks or try-with-resources. This can add extra code and may be confusing for beginners. - More Verbose than Scanner
Unlike Scanner, which can directly read integers or doubles, BufferedReader only reads strings. Developers must manually parse data types, which leads to more code and less convenience.
Frequently Asked Questions
What is the purpose of the BufferedReader class in Java?
The BufferedReader class in Java is used to read text from a character-based input stream efficiently by buffering the input. It provides methods to read data line by line or character by character.
What is the difference between BufferedReader and FileReader?
FileReader is used to read characters from a file, while BufferedReader wraps around a Reader (such as FileReader) to provide buffering functionality. BufferedReader improves reading performance by reducing the number of I/O operations.
Do I need to close the BufferedReader after using it?
Yes, it is important to close the BufferedReader when you're done using it to release any system resources associated with it. Failing to close the reader may lead to resource leaks in your program.
Conclusion
In this article, we discussed the BufferedReader class in Java, which provides an efficient way to read text from character-based input streams. We learned about the class declaration, constructors, and methods of BufferedReader. We also saw different examples of using BufferedReader to read data from files and the console. By wrapping a Reader with BufferedReader, we can improve reading performance and easily read lines of text, but always remember to close the BufferedReader when you're done to release system resources.