Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

The important points about BufferedInputStream are:

  • When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
  • When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration

Let's see the declaration for Java.io.BufferedInputStream class:

  1. public class BufferedInputStream extends FilterInputStream  

Java BufferedInputStream class constructors



BufferedInputStream(InputStream IS)

It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, int size)

It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

Java BufferedInputStream class methods



int available()

It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.

int read()

It read the next byte of data from the input stream.

int read(byte[] b, int off, int ln)

It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.

void close()

It closes the input stream and releases any of the system resources associated with the stream.

void reset()

It repositions the stream at a position the mark method was last called on this input stream.

void mark(int readlimit)

It sees the general contract of the mark method for the input stream.

long skip(long x)

It skips over and discards x bytes of data from the input stream.

boolean markSupported()

It tests for the input stream to support the mark and reset methods.

Example of Java BufferedInputStream

Let's see the simple example to read data of file using BufferedInputStream:

  1. package com.javatpoint;  
  3. import java.io.*;  
  4. public class BufferedInputStreamExample{    
  5.  public static void main(String args[]){    
  6.   try{    
  7.     FileInputStream fin=new FileInputStream("D:\testout.txt");    
  8.     BufferedInputStream bin=new BufferedInputStream(fin);    
  9.     int i;    
  10.     while((i=bin.read())!=-1){    
  11.      System.out.print((char)i);    
  12.     }    
  13.     bin.close();    
  14.     fin.close();    
  15.   }catch(Exception e){System.out.println(e);}    
  16.  }    
  17. }  

Here, we are assuming that you have following data in "testout.txt" file: