Home » Java programming language

Java InputStream available() Method with Example

InputStream Class available() method: Here, we are going to learn about the available() method of InputStream Class with its syntax and example.
Submitted by Preeti Jain, on April 03, 2020

InputStream Class available() method

  • available() method is available in java.io package.
  • available() method is used to return the number of available bytes left for reading from this InputStream without blocking by the next call of the method from this InputStream.
  • available() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • available() method may throw an exception at the time of returning available bytes.
    IOException: This exception may throw when getting any input/output error.

Syntax:

    public int available();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of the method is int, it returns the number of bytes left that can be read.

Example:

// Java program to demonstrate the example 
// of int available() method of InputStream

import java.io.*;

public class AvailableOfIS {
 public static void main(String[] args) throws Exception {
  InputStream is_stm = null;
  int val = 0;

  try {
   // Instantiates FileInputStream
   is_stm = new FileInputStream("D:\\includehelp.txt");

   // Loop to read until available
   // bytes left
   while ((val = is_stm.read()) != -1) {

    // By using available() method is to
    // return the available bytes to be read

    int avail_bytes = is_stm.available();

    // Display corresponding byte value
    byte b = (byte) val;

    // Display value of avail_bytes and b
    System.out.print("is_stm.available(): " + avail_bytes);
    System.out.println(" : " + "byte: " + b);
   }

  } catch (Exception ex) {
   System.out.println(ex.toString());

  } finally {
   // with the help of this block is to
   // free all necessary resources linked
   // with the stream
   if (is_stm != null) {
    is_stm.close();
   }
  }
 }
}

Output

is_stm.available(): 3 : byte: 74
is_stm.available(): 2 : byte: 65
is_stm.available(): 1 : byte: 86
is_stm.available(): 0 : byte: 65


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.