Home » Java programming language

Java FileInputStream available() Method with Example

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

FileInputStream Class available() method

  • available() method is available in java.io package.
  • available() method is used to return the number of bytes left that can be read from this FileInputStream and without blocking by the next invocation of this method for this FileInputStream.
  • 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 while getting any input/output error or when this stream is closed by the close() method.

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 available bytes left that can be read from this FileInputStream during unblock.

Example:

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

import java.io.*;

public class AvailableOfFIS {
 public static void main(String[] args) throws Exception {
  FileInputStream fis_stm = null;
  int count = 0;

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

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

    // By using available() method is to
    // return the available bytes to be read
    int avail_bytes = fis_stm.available();

    // Display corresponding bytes value
    byte b = (byte) count;

    // Display value of avail_bytes and b
    System.out.print("fis_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 (fis_stm != null) {
    fis_stm.close();
   }
  }
 }
}

Output

fis_stm.available(): 15 : byte: 0
fis_stm.available(): 14 : byte: 4
fis_stm.available(): 13 : byte: 74
fis_stm.available(): 12 : byte: 97
fis_stm.available(): 11 : byte: 118
fis_stm.available(): 10 : byte: 97
fis_stm.available(): 9 : byte: 0
fis_stm.available(): 8 : byte: 8
fis_stm.available(): 7 : byte: 87
fis_stm.available(): 6 : byte: 111
fis_stm.available(): 5 : byte: 114
fis_stm.available(): 4 : byte: 108
fis_stm.available(): 3 : byte: 100
fis_stm.available(): 2 : byte: 33
fis_stm.available(): 1 : byte: 33
fis_stm.available(): 0 : byte: 33


Comments and Discussions!

Load comments ↻





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