BufferedReader Class in Java

The BufferedReader class in Java, located in the java.io package, is used to read text from a character-input stream efficiently. It provides buffering capabilities, which means it reads a chunk of characters from the underlying input stream and stores them in an internal buffer. This buffering reduces the number of read requests to the underlying stream, making it more efficient for reading larger amounts of data.

How to use Java Bufferedreader
BufferedReader br = new BufferedReader(new FileReader("test.txt"));

Buffer Size

The buffer size is an important aspect of BufferedReaders in Java. Let's explore it further:

Specifying Buffer Size

When creating a BufferedReader, you have the option to specify a custom buffer size by providing the desired size as an argument to the constructor.

BufferedReader br = new BufferedReader(new FileReader("file.txt"), bufferSize);
  1. Default Buffer Size: If you do not explicitly specify a buffer size, the BufferedReader will use the default buffer size, which is usually large enough for most purposes. The default buffer size in Java is 8192 characters.
  2. Custom Buffer Size Benefits: There might be scenarios where using a custom buffer size can provide performance advantages. For example, if you are dealing with very large files or streams and have enough memory available, increasing the buffer size could lead to faster reading operations.
  3. Resource Considerations: While a larger buffer size can improve performance, it's essential to consider available memory resources. If the buffer size is too large, it may consume a significant amount of memory, potentially leading to OutOfMemoryError, especially when handling multiple large files or streams simultaneously.
  4. Optimizing Buffer Size: The optimal buffer size depends on factors such as the size of the data being read, the available memory, and the I/O performance characteristics of the underlying storage (e.g., disk speed, network bandwidth). It might require some experimentation to find the most suitable buffer size for specific use cases.

Default Buffer Size Override

In some cases, you may want to override the default buffer size to better suit your application's requirements. To do so, you can use the public void setBufferSize(int size) method of the BufferedReader class.

BufferedReader br = new BufferedReader(new FileReader("file.txt")); br.setBufferSize(customBufferSize);

The ability to specify a custom buffer size gives developers more control over the performance of their file and streamed reading tasks. Careful consideration of the buffer size can help optimize the reading process and make the most efficient use of available resources.

The following Java program read input from console and display it using BufferedReader:

import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(System.in)); String str; str = br.readLine(); System.out.println("You entered :: " + str); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }

The following java program read text from an external file and display the text using BufferedReader:

import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("D:\\test.txt")); while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }

Key advantages of using BufferedReaders in Java

Let's explore more detail about why BufferedReaders are preferable for demanding tasks, such as file and streamed reading:

  1. Efficient Reading: BufferedReaders optimize input and output by reducing the number of calls to the native API. When you read data from an input stream, it involves interacting with the underlying operating system, which can be relatively slow. By buffering the data, the BufferedReader reads a larger chunk of data at once, minimizing the number of interactions with the OS and improving performance.
  2. Reduced Disk I/O: When reading from disk files, BufferedReaders read larger chunks of data into memory and then access the data from memory, rather than repeatedly accessing the disk for each individual read. Disk I/O operations are typically slower than accessing data from memory, so buffering the reads can significantly reduce the overhead associated with disk I/O.
  3. Network Communications Optimization: In the case of reading from network streams, BufferedReaders can help optimize the data transfer process. Network communications can be slower compared to reading from memory, so buffering the data allows for more efficient handling of the data received over the network.
  4. Reduced Latency: Buffering the reads allows the data to be loaded into faster RAM (Random Access Memory) instead of being processed directly from slower storage devices like disk or network sockets. This reduces the latency and access times, leading to faster data processing.
  5. Fewer Native API Calls: The native API calls involve communication between Java and the operating system, and these calls have an overhead. By reducing the number of native API calls, BufferedReaders can reduce this overhead and improve the overall performance of the I/O operations.

It's important to handle exceptions properly, as shown in the try-catch block, to ensure that the program doesn't crash if there are any issues with reading the file. Also, don't forget to close the BufferedReader using the close() method when you're done reading to release any resources it may be holding.

Conclusion

The BufferedReader class is particularly useful when reading large text files or when you need to read line-by-line efficiently. It can be used in various scenarios, such as reading configuration files, processing log files, or parsing CSV data.