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.
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.
Original File content: file.txt
This program will read a file and returns how many characters are left to read every time.
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