FileInputStream available() Method in Java with Examples
The available() method of FileInputStream class is used to return the estimated number of remaining bytes that can be read from the input stream without blocking. This method returns the number of bytes remaining to read from the file. When a file is completely read, this function returns zero.
Syntax:
FileInputStream available()
Return Value: The method returns and estimates the number of remaining bytes read from this input stream without blocking.
Exception: This method can generate exceptions like IOException or FileNotFoundException.These exceptions are described below.
- IOException – If the file input stream has been closed by calling close or any I/O error occurs.
- FileNotFoundException – If that directory is not available, then we will get FileNotFoundException.
How to invoke the available() Method?
Step 1: Attach a file to a FileInputStream as this will enable us to read data from the file as shown below as follows:
FileInputStream fileInputStream = new FileInputStream(“file.txt”);
Step 2: Now, to read data from the file that how much data is available for reading, we should call an available method using FileInputStream object like below;
int ch = fileInputStream.available();
Step 3(a): When there is no more data available to read further, the available() method returns 0;
Step 3(b): Then, we should attach the monitor to the output stream. For displaying the data, we can use System.out.print.
System.out.print(ch);
Implementation
Original File content: file.txt
GeeksforGeeks
This program will read a file and returns how many characters are left to read every time.
Java
import java.io.File;
import java.io.FileInputStream;
public class abc {
public static void main(String[] args)
{
File file = new File( "file.txt" );
try {
FileInputStream input = new FileInputStream(file);
int character;
while ((character = input.read()) != - 1 ) {
int ch = input.available();
System.out.print( "Currently Reading:"
+ ( char )character);
System.out.print( " Remaining character: "
+ ch);
System.out.println();
}
input.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output
Currently Reading:G Remaining character: 12
Currently Reading:e Remaining character: 11
Currently Reading:e Remaining character: 10
Currently Reading:k Remaining character: 9
Currently Reading:s Remaining character: 8
Currently Reading:f Remaining character: 7
Currently Reading:o Remaining character: 6
Currently Reading:r Remaining character: 5
Currently Reading:G Remaining character: 4
Currently Reading:e Remaining character: 3
Currently Reading:e Remaining character: 2
Currently Reading:k Remaining character: 1
Currently Reading:s Remaining character: 0
Last Updated :
29 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...