Java.io.BufferedInputStream.available() Method

Advertisements


Description

The java.io.BufferedInputStream.available() method returns the number of bytes remained to read from an input stream without blocking by the next invocation of a method for this input stream.

Declaration

Following is the declaration for java.io.BufferedInputStream.available() method

public int available()

Return Value

This method returns number of bytes remained to read from this input stream without blocking.

Exception

  • IOException -- -- if an I/O error occurs..

Example

The following example shows the usage of java.io.BufferedInputStream.available() method.

package com.tutorialspoint;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BufferedInputStreamDemo {
   public static void main(String[] args) throws Exception {

      InputStream inStream = null;
      BufferedInputStream bis = null;

      try{
         // open input stream test.txt for reading purpose.
         inStream = new FileInputStream("c:/test.txt");

         // input stream is converted to buffered input stream
         bis = new BufferedInputStream(inStream);      

         // read until a single byte is available
         while( bis.available() > 0 )
         {
            // get the number of bytes available
            Integer nBytes = bis.available();
            System.out.println("Available bytes = " + nBytes );

            // read next available character
            char ch =  (char)bis.read();

            // print the read character.
            System.out.println("The character read = " + ch );
         }
      }catch(Exception e){
         e.printStackTrace();
      }finally{
         
         // releases any system resources associated with the stream
         if(inStream!=null)
            inStream.close();
         if(bis!=null)
            bis.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE 

Let us compile and run the above program, this will produce the following result:

Available bytes = 5
The character read = A
Available bytes = 4
The character read = B
Available bytes = 3
The character read = C
Available bytes = 2
The character read = D
Available bytes = 1
The character read = E



Advertisements
Advertisements