BufferedInputStream in Java



BufferedInputStream File Java

BufferedInputStream in Java

BufferedInputStream is a class in Java which we can use to read data from a file stream. We can use FileInputStream as the input stream along with the BufferedInputStream. It uses the concept of a buffer where it creates a buffer array whenever we create a BufferedInputStream. Whenever we call the read method, it reads a group of bytes from the disk and stores it in the internal buffer. Hence it reads the data from the buffer which reduces the call to the disk. This makes the performance much faster.

BufferedInputStream in Java

Constructor

Below are the constructors of the BufferedInputStream class in Java:

ConstructorDescription
BufferedInputStream(InputStream is)Creates a BufferedInputStream and saves the 'is' stream for later use
BufferedInputStream(InputStream is, int size)Creates a BufferedInputStream with a specified size and stores the 'is' parameter stream for later use

BufferedInputStream methods

MethodDescription
int available()Returns the estimate number of bytes available to read
void close()Closes the BufferedInputStream
void mark(int readLimit)Marks the current position to read from the input stream
boolean markSupported()Checks whether the stream supports the mark() and reset() methods
int read()Reads a byte of data from the input stream
int read(byte[] b)Reads the specified byte from the input array
int read(byte[] b, int off, int len)Reads the len bytes of data from the array starting from specified off position
byte[] readAllBytes()Reads all the remaining bytes from the input stream
byte[] readNBytes(int len)Reads upto the specified number of bytes
int readNBytes(bytes[]b, int off, int len)Reads upto the specified length of bytes from the byte array starting from the offset position.
long skip(long n)Slips or discards the specified number of bytes during the read operation
void skipNBytes(long n)Skips or discards upto the specified number of bytes during the read operation
long transferTo(OutputStream out)Reads all the bytes from the input stream and writes it to the specified output stream in the same order

Example: Read data from a file using Java BufferedInputStream

The below example reads the contents of the file until the read() method returns -1 which is the end of the file. It converts the integer value to a character and then prints the information. The input file contains the information “This is an example of BufferedInputStream”.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFile {

  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    BufferedInputStream bi = new BufferedInputStream(fi);
    
    try {
      int i;
      while((i=bi.read()) != -1) {
        System.out.print((char)i);
      }
      
      bi.close();
      fi.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }

}
This is an example of BufferedInputStream

Below is another example to read the contents of a file using the available method. The available method returns a value greater than 0 if there are more bytes to read. Hence using a while loop, we can read the contents of a file until the available method returns a negative value.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFile {

  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    BufferedInputStream bi = new BufferedInputStream(fi);
    
    try {
      while(bi.available() > 0)
        System.out.print((char)bi.read());
      
      bi.close();
      fi.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
This is an example of BufferedInputStream

Example: Read the specific length of data from a file

The below example shows how to read a specific length of data from a file using the read() method of the BufferedInputStream class in Java. Here, we have allocated only 10 bytes, out of which we read 8 bytes starting from the 0 position. Hence it prints only “This is **” by filling the remaining 2 bytes of data with “*”.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFile {

  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    BufferedInputStream bi = new BufferedInputStream(fi);
    
    try {
      byte[] b = new byte[10];
      int a = bi.read(b, 0, 8);
      for(byte by : b) {
        char ch = (char)by;
        if(by == 0)
          ch = '*';
        System.out.print(ch);
      }
      
      bi.close();
      fi.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
This is **

Example: Java BufferedInputStream available() method

The available() method of the BufferedInputStream class returns the estimated number of bytes remaining to read from the input stream. Initially, it holds the total number of bytes available before the read operation. Based on the number of bytes read, it returns the estimated number of bytes remaining to read. We can understand this clearly with an example below.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CheckAvailableBytes {

  public static void main(String[] args) throws IOException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    BufferedInputStream bi = new BufferedInputStream(fi);
    int a = 0;
    
    System.out.println("Available bytes before read operation: " + bi.available());
    System.out.print((char)bi.read());
    System.out.print((char)bi.read());
    System.out.print((char)bi.read());
    System.out.print((char)bi.read());
    
    System.out.println("\nAvailable bytes after read operation: " + bi.available());
    bi.close();
    fi.close();
  }

}
Available bytes before read operation: 41
This
Available bytes after read operation: 37

Example: Java BufferedInputStream skip() method

The below example illustrates the working of the skip() method in the Java BufferedInputStream class. Based on the number passed as a parameter in the skip() method, it discards that many numbers of bytes to read. Here, we discard the first 4 bytes of data to read and continue reading the remaining bytes using the read() method.

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class SkipDemo {

  public static void main(String[] args) throws IOException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    BufferedInputStream bi = new BufferedInputStream(fi);
    
    try {
      bi.skip(4);
      System.out.println("Contents after skipping 4 bytes:");
      int a = 0;
      while((a=bi.read()) != -1)
        System.out.print((char)a);
      bi.close();
      fi.close();
      
      
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}
Contents after skipping 4 bytes:
 is an example of BufferedInputStream

 

Reference

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions