BufferedInputStream in Java | Methods, Example

A BufferedInputStream in Java is a concrete subclass of FilterInputStream that wraps (buffers) an input stream into a buffered stream and makes read operations on the stream more efficient and fast.

In simple words, it adds buffering capabilities to an input stream that stores data (in bytes) temporarily into a memory buffer by reading from the stream.

It is used to speed up the input by reducing the number of disk or file reads by adding an additional layer of functionality around the underlying stream.

For example, FileInputStream and FileOutputStream in Java are unbuffered, meaning that each read and write request is handled directly by the operating system.

It makes the program less efficient because for every read or write request, they will access a disk or file. It will waste a lot of time.

On the other hand, if we buffer input data from a file by wrapping a FileInputStream (for instance) into a BufferedInputStream, the buffered stream will store data into a temporary block of buffered memory.

And then data is sent individually to the program from the buffer. Thus, buffered input stream in Java makes file operations more efficient and fast.

Working of BufferedInputStream in Java


In Java BufferedInputStream, a buffer is internally between the program and the source. During the read operation, the whole block of data (in bytes) is read from the disk and temporarily stored into the internal buffer in the memory once.

The data are then transferred (read) individually to the program from the buffer, as shown in Figure below.

BufferedInputStream class in Java

The key points about BufferedInputStream in Java are:

  • When the input data (in bytes) from the stream are skipped or read, the buffered stream automatically refilled many data from the input stream at a time.
  • When a BufferedInputStream object is created, a buffer array is created internally.
  • Buffers can be constructed by using BufferedInputStream and BufferedOutputStream classes.

Java BufferedInputStream class declaration


BufferedInputStream class is derived from class FilterInputStream, which has InputStream as a base class. It implements Closeable and AutoCloseable interfaces.


The general declaration of BufferedInputStream class is as follows:

public class BufferedInputStream 
    extends FilterInputStream  
        implements Closeable, AutoCloseable

BufferedInputStream was added in Java 1.0 version. It is present in java.io.BufferedInputStream package.

Constructor of BufferedInputStream Class


To wrap InputStream, BufferedInputStream class defines two constructors that are as follows:

1. BufferedInputStream(InputStream inputStream): This constructor creates a BufferedInputStream object that buffers an input stream specified by inputStream. It uses default buffer size. The default internal buffer size is 8192 bytes.

The general syntax to wrap FileInputStream into BufferedInputStream is as follows:

// Creates an instance of FileInputStream with specified file path.
     FileInputStream fis = new FileInputStream(String path);

// Creates a BufferedInputStream object and passes reference variable fis to its constructor.
// Wrapping the file stream in a BufferedInputStream.
     BufferedInputStream buffer = new BufferInputStream(fis); 

2. BufferedInputStream(InputStream inputStream, int size): This constructor creates a BufferedInputStream object that buffers an input stream with a specified buffer size.

The general syntax to wrap FileInputStream into the buffered stream is as follows:

// Creates a BufferedInputStream object with specified size of internal buffer. 
     BufferedInputStream buffer = new BufferInputStream(fis, int size);

Now, perform all I/O operations through the buffered stream. At last, close the buffered stream by calling the close() method.


Closing the buffered stream automatically closes the underlying file stream. An exception named IOException will be thrown if an error occurs.

BufferedInputStream Methods in Java


BufferedInputStream class does not define any new methods. All the methods in BufferedInputStream are inherited from the InputStream class. Some important methods are as follows:

1. int available(): This method returns the number of available bytes from the input stream without being blocked.

2. int read(): This method reads the next byte of data from the buffered input stream.

3. read(byte[ ] arr): It reads bytes from the buffered input stream and stores them in the specified array.

4. int read(byte[ ] b, int n, int m): It reads up to m bytes of data from this input stream and stores it into an array of bytes starting from the nth byte.

5. void close(): This method closes the buffered input stream and releases any of the system resources associated with the stream.

6. void reset(): It repositions the buffered input stream to the last marked position.

7. long skip(long x): This method skips over and discards x bytes of data from the buffered input stream.

8. void mark(int readlimit): This method marks the current position in the buffered input stream.

9. boolean markSupported(): It tests whether the buffered input stream supports the mark and reset methods.

Example Program based on Java BufferedInputStream


1. Let’s take a simple example program to read data from a file myfile using BufferedInputStream. Look at the source code to understand better.

Program source code 1:

package javaProgram;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class BufferedInputStreamEx {
public static void main(String[] args)
{
 try
 {
// Create a FileInputStream object to attach myfile to FileInputStream.	 
   FileInputStream fis = new FileInputStream("D:\\myfile.txt");
  
// Create a BufferedInputStream object to wrap FileInputStream in BufferedInputStream.
   BufferedInputStream bis = new BufferedInputStream(fis);
  
 int i = 0;
 while ((i = bis.read()) != -1) {
  char ch = (char)i;
  System.out.println(ch);
 }     
  bis.close();
  fis.close();  
}catch(Exception e)
 {
	System.out.println(e);
 }
 }}
Output:
       Welcome to Scientech Easy

In this example program,

1. We have created a buffered input stream named bis and connected it to FileInputStream fis.

2. Then, we have used a while loop and read() method to read all bytes from the internal buffer and display them on the console.

Here, we are assuming that you have the following data in “myfile.txt” file: Welcome to Scientech Easy.


2. Let’s create a program to get the number of available bytes in the input stream. For this purpose, we will use available() method.

Program source code 2:

package javaProgram;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class BufferedInputStreamEx {
public static void main(String[] args)
{
 try
 {
// Create a FileInputStream object to attach myfile to FileInputStream.	 
   FileInputStream fis = new FileInputStream("D:\\myfile.txt");
  
// Create a BufferedInputStream object to wrap FileInputStream in BufferedInputStream.
   BufferedInputStream bis = new BufferedInputStream(fis);
 
// Call available() method to determine the available number of bytes in bufferedInputStream.
   System.out.println("Available bytes at the beginning: " + bis.available());  
 
// Reads bytes from the file
   bis.read();
   bis.read();
   bis.read();
 
// Get the available number of bytes at the end.
   System.out.println("Available bytes at the end: " + bis.available());
    bis.close();  
}catch(Exception e)
 {
   System.out.println(e);
 }
 }}
Output:
      Available bytes at the beginning: 25
      Available bytes at the end: 22

In this example program,

1. We first use the available() method to check the number of available bytes in the buffered input stream.

2. Then, we have used the read() method 3 times to read 3 bytes from the buffered input stream.

3. After reading three bytes, we again have checked the available number of bytes in the input stream. This time the available number of bytes is 22.


3. Let’s create a program to discard and skip the specified number of bytes from the input stream. For this purpose, we will use skip() method.

Program source code 3:

package javaProgram;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class BufferedInputStreamEx {
public static void main(String[] args)
{
 try
 {
// Create a FileInputStream object to attach myfile to FileInputStream.	 
   FileInputStream fis = new FileInputStream("D:\\myfile.txt");
  
// Create a BufferedInputStream object to wrap FileInputStream in BufferedInputStream.
   BufferedInputStream bis = new BufferedInputStream(fis);
 
// Skips 5 bytes from the buffered input stream.
   bis.skip(5);
   System.out.println("Input stream after skipping first 5 bytes:");

// Reads all available bytes from buffered input stream after skipping.
   int i = 0;
   while ((i = bis.read()) != -1) {
    System.out.print((char) i);
   }
    bis.close();  
}catch(Exception e)
 {
   System.out.println(e);
 }
 }
}
Output:
      Input stream after skipping first 5 bytes:
      me to Scientech Easy

In this example program, we have used skip() method for skipping the first 5 bytes from the buffered input stream and display the rest on the console. The skipping bytes are ‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, and ‘ ‘.


Hope that this tutorial has covered almost all the important points concerning BufferedInputStream in Java with example programs. I hope that you will have understood the basics points of BufferedInputStream class and its example programs.
Thanks for reading!!!
Next ⇒ BufferedOutputStream in Java

⇐ Prev Next ⇒