The Buffered Streams BufferedInputStream - RameshMF/java-io-guide GitHub Wiki

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.

BufferedInputStream class Constructors

  • BufferedInputStream(InputStream in) - Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
  • BufferedInputStream(InputStream in, int size) - Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.

BufferedInputStream class Methods

  • int available() - Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
  • void close() - Closes this input stream and releases any system resources associated with the stream.
  • void mark(int readlimit) - See the general contract of the mark method of InputStream.
  • boolean markSupported() - Tests if this input stream supports the mark and reset methods.
  • int read() - See the general contract of the read method of InputStream.
  • int read(byte[] b, int off, int len) - Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.
  • void reset() - See the general contract of the reset method of InputStream.
  • long skip(long n) - See the general contract of the skip method of InputStream.

BufferedInputStream class Example

This program is to read file "sample.txt" and print output to console.

The "sample.txt" file contains the below text in it.

Note : This program uses try-with-resources. It requires JDK 7 or later.

This is the text content
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * The class demonstrate the usage of BufferedInputStream class methods.
 * @author javaguides.net
 *
 */

public class BufferedInputStreamExample {
	public static void main(String[] args) {
		try( FileInputStream fin=new FileInputStream("sample.txt");    
			    BufferedInputStream bin=new BufferedInputStream(fin); ){
			int i;    
		    while((i=bin.read())!=-1){    
		     System.out.print((char)i);    
		    }    
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output:

This is the text content

Reference

BufferedInputStream