What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

BufferedReader Class in Java (with Examples)

  • Dec 04, 2023
  • 10 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Nihal Mahansaria
BufferedReader Class in Java (with Examples)

In Java, input streams serve as the primary means of reading data from various sources, including files, user input, or network connections. These streams facilitate the sequential reading of data in a byte-oriented manner. In this article, we will learn everything about the BufferedReader class in Java with examples.

What is BufferedReader Class in Java?

Reading data directly from streams can be inefficient due to frequent disk or network access, especially when dealing with small roads. Buffered input aims to enhance performance by reducing the number of I/O operations through temporary storage.

BufferedReader is a Java class that provides buffered reading functionality, improving efficiency by minimizing the frequency of I/O operations. It reads data from an underlying Reeder instance, allowing the reading of characters, strings, or lines efficiently.

It provides several advantages, including improved efficiency by minimizing I/O operations, enhanced performance via buffering, and the ability to read data as characters, strings, or lines. It internally uses a buffer to read data from the underlying input stream, reducing the number of system calls and enhancing speed.

BufferReader offers various methods such as read(), readLine(), and read(char[] cbuf, int off, int len) to read data efficiently. For instance, readLine() reads a line of text and returns it as a string, while read(char[] cbuf, int off, int len) reads characters into an array.

try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line); // Prints each line read from the file
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

This code snippet demonstrates how to use BufferedReader to read lines from a file efficiently, displaying each line read onto the console.

BufferedReader utilizes an internal buffer, enabling it to read larger chunks of data from the underlying stream at once. This buffering mechanism significantly reduces the overhead of frequent disk or network access, enhancing reading performance.

Methods and Operations in BufferedReader

Let’s look at the methods and operations in BufferedReader.

  1. Reading Lines and Characters

BufferedReader provides several methods for reading data. The readLine() method reads a line of text as a string. For character-based reading, read() reads a single character and returns its Unicode value, while read(char[] cbuf, int off, int len) reads characters into an array.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
    System.out.print("Enter your name: ");
    String name = reader.readLine(); // Reads a line of text from the console
    System.out.println("Hello, " + name + "!");
} catch (IOException e) {
    e.printStackTrace();
}

 

In this example, BufferedReader reads a line of text entered by the user in the console.

  1. Skipping and Marking

BufferedReader supports the skip(long n) method, which skips characters in the input stream, and the mark(int readAheadLimit) method, allowing marking the present position in the stream to return to it later.

BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
try {
    reader.skip(50); // Skips the first 50 characters
    reader.mark(100); // Marks the current position for later use
    // Read operations from the marker position
    // ...
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close(); // Closing the BufferedReader
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

These methods offer flexibility in handling input streams, enabling skipping and marking positions for future reading operations.

  1. Closing BufferedReader

It's essential to close BufferedReader instances to release system resources. Using the try-with-resources statement ensures proper resource management by automatically closing the stream after its use.

try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
    // Read operations
} catch (IOException e) {
    e.printStackTrace();
}

 

The try-with-resources statement ensures the automatic closure of the BufferedReader instance, improving resource management and preventing resource leaks.

Handling Errors and Exceptions in BufferedReader

BufferedReader methods can throw Exceptions due to various reasons such as I/O errors, reaching the end of the stream, or file-related issues. Proper exception handling ensures graceful error recovery.

Let's look at an example:

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("example.txt"));
    // Read operations
} catch (FileNotFoundException e) {
    System.err.println("File not found: " + e.getMessage());
} catch (IOException e) {
    System.err.println("Error reading the file: " + e.getMessage());
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

Handling specific exceptions such as FileNotFoundException or IOException allows for appropriate error messages and recovery actions.

It's considered good practice to handle exceptions gracefully, providing informative error messages to aid debugging. Additionally, closing the BufferedReader instance in a final block ensures proper resource cleanup.

Use Cases of Java BufferedReader Class

Following are some of the main use cases of Bufferedreader class in Java:

One of the most common applications of BufferedReader is reading data from files. It's used for file input operations, enabling efficient reading of text files or structured data from various sources.

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // Process each line from the file
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

Also, it facilitates reading user input from the console, enabling interactive command-line applications that prompt users for input and process it efficiently.

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
    System.out.print("Enter your age: ");
    String ageStr = reader.readLine();
    int age = Integer.parseInt(ageStr);
    // Further processing based on user input
} catch (IOException | NumberFormatException e) {
    e.printStackTrace();
}

 

Conclusion

BufferedReader in Java plays a pivotal role in efficient input reading by enhancing performance and providing functionalities to read data from various sources like files, user input, or network connections.  It enable developers to handle input streams effectively. Its ability to read data in a buffered manner improves reading efficiency, making it a valuable tool in Java for handling diverse input scenarios. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Nihal Mahansaria
As a computer science student with a passion for technology and a drive to learn, I have developed a diverse set of skills in web development, machine learning, and technical content writing. With experience in multiple front-end and back-end frameworks, including Flask and Python, I am able to create scalable and efficient web applications.