Open In App

Java BufferedInputStream available() method with Example

Last Updated : 03 Jan, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The BufferedInputStream class adds new attributes to other input streams, an ability to buffer the input. When BufferedInputStream is created, an internal buffer array is created.

The available() method of BufferedInputStream class is used to know the number of bytes available to read from the internal buffer array, until a situation arises where there is no data available to read. The invocation of the method read() will block the execution flow of the program and wait for the data to be made available.

Syntax:

public int available()

Parameters: This method does not take any parameters.

Return value: The method is used to return the sum of bytes remained to be read from this input stream without any blockage.

Exception: The method throws IOException if an error related to input-output occurs or when the close method has been used to close the input stream.

Example 1: Below program illustrates the use of available() method, assuming the existence of file “d:/demo.txt”.




// Java code to illustrate available() method
import java.io.*;
class Testing {
    public static void main(String[] args)
    throws IOException
    {
   
        // create input stream 'demo.txt'
        // for reading containing text "GEEKS"
        FileInputStream inputStream = 
        new FileInputStream("d:/demo.txt");
   
        // convert inputStream to 
        // bufferedInputStream
        BufferedInputStream buffInputStr = 
        new BufferedInputStream(inputStream);
   
        // get the number of bytes available
        // to read using available() method
        Integer remBytes = 
        buffInputStr.available();
   
        // Print result
        System.out.println(
            "Remaining bytes =" + remBytes);
    }
}


Output:

5

Example 2: Below program illustrates the use of available() method, assuming the existence of file “d:/demo.txt”.




// Java code to illustrate available() method
import java.io.*;
class Testing {
    public static void main(String[] args)
    throws IOException
    {
   
        // create input stream demo.txt
        // for reading containing text
        // "GEEKSFORGEEKS"
        FileInputStream inputStream =
        new FileInputStream("d:/demo.txt");
   
        // convert inputStream to 
        // BufferedInputStream
        BufferedInputStream buffInputStr =
        new BufferedInputStream(inputStream);
   
        // get the number of bytes available to
        // read using available() method
        Integer remBytes = 
        buffInputStr.available();
   
        // Print result
        System.out.println(
            "Remaining bytes =" + remBytes);
    }
}


Output:

13


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads