Java Code Example for BufferedInputStream: read() Method

read() method of BufferedInputStream class reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

/*
 * *********************************************************************************
 *  * 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:48 PM
 */
public class BufferedInputStreamRead {
    /**
	 * @param args
	 */
	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);
			}
		}
	}
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.