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.
Parameters:
b – destination buffer.
off – offset at which to start storing bytes.
len – maximum number of bytes to read.
[java]
/*
* *********************************************************************************
* * Created on 2011 Copyright(c) https://kodehelp.com All Rights Reserved.
* *********************************************************************************
*/
import java.io.*;
/**
* Created by Vigilance.co.in
* User: https://kodehelp.com
* 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;
try
{
//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 = bufferedInputStream.read(buffer,0,1)) != -1 ){
strFileContents = new String(buffer, 0, bytesRead);
System.out.print(strFileContents);
}
}catch(FileNotFoundException e){
System.out.println(“File not found” + e);
}catch(IOException ioe){
System.out.println(“Exception while reading the file ” + ioe);
}finally{
//close the BufferedInputStream using close method
try{
if(bufferedInputStream != null)
bufferedInputStream.close();
}catch(IOException ioe){
System.out.println(“Error while closing the stream : ” + ioe);
}
}
}
}
[/java]