BufferedInputStream adds an additionally capability to InputStream by buffering the input. When instance of BufferedInputStream is created, an internal array is created to buffer the input data. As bytes from stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time. BufferedInputStream class has below methods –
Below code example show the how to read the file using bufferedInputStream :
[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: 12:07 PM
*/
public class ReadUsingBufferedInputStream {
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);
/*
* BufferedInputStream has ability to buffer input into
* internal buffer array.
*
* available() method returns number of bytes that can be
* read from underlying stream without blocking.
*/
//read file using BufferedInputStream
while( bufferedInputStream.available() > 0 ){
System.out.print((char)bufferedInputStream.read());
}
}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]