Java Code Example for BufferedInputStream: read(byte[] b,int off,int len) Method

Reads bytes from this byte-input stream into the specified byte array, starting at the given offset. It attempts to read as many bytes as possible by repeatedly invoking the read method of the underlying stream. This iterated read continues until one of the following conditions becomes true:

  • The specified number of bytes have been read,
  • The read method of the underlying stream returns -1, indicating end-of-file, or
  • The available method of the underlying stream returns zero, indicating that further input requests would block.

If the first read on the underlying stream returns -1 to indicate end-of-file then this method returns -1. Otherwise this method returns the number of bytes actually read.

b – destination buffer.
off – offset at which to start storing bytes.
len – maximum number of bytes to read.

* *********************************************************************************
* * Created on 2011 Copyright(c) All Rights Reserved.
* *********************************************************************************


* Created by
* User:
* Date: 3/21/11
* Time: 1:57 PM

public class BufferedInputStreamReadByte {

public static void main(String[] args) {
//create file object
File file = new File(“/test.txt”);
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;

//create FileInputStream object
fileInputStream = new FileInputStream(file);
//create BufferedInputStream object
bufferedInputStream = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[1024];
int bytesRead=0;
String strFileContents;
* BufferedInputStream has ability to buffer input into
* internal buffer array.
* read(byte[] b, int off, int len) method reads the number of bytes specified in len
* and starts the reading at offset off into byte array b

//read file using BufferedInputStream
while( (bytesRead =,0,1)) != -1 ){
strFileContents = new String(buffer, 0, bytesRead);

}catch(FileNotFoundException e){
System.out.println(“File not found” + e);
}catch(IOException ioe){
System.out.println(“Exception while reading the file ” + ioe);
//close the BufferedInputStream using close method
if(bufferedInputStream != null)
}catch(IOException ioe){
System.out.println(“Error while closing the stream : ” + ioe);