Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

FileInputStream close() Method in Java with Examples

  • Last Updated : 01 Dec, 2021

FileInputStream class is helpful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

FileInputStream.close() method 

After any operation to the file, we have to close that file. For that purpose, we have a close method. We will learn that in this article. The FileInputStream.close() method closes this file input stream and releases any system resources associated with the stream.

Syntax:

FileInputStream.close()

Return Value: The method does not return any value.

Exception: IOException − If any I/O error occurs.

How to invoke the close() method?

Step 1: Attach a file to a FileInputStream as this will enable us to close the file as shown below as follows:

FileInputStream  fileInputStream =new FileInputStream(“file.txt”);

Step 2: To close the file, we have to call the close() method using the above instance.

fileInputStream.close(); 

Approach:

1. We will first read a file and then close it.

2. After closing a file, we will again try to read it.

Java




// Java program to demonstrate the working
// of the FileInputStream close() method
  
import java.io.File;
import java.io.FileInputStream;
  
public class abc {
  
    public static void main(String[] args)
    {
  
        // Creating file object and specifying path
        File file = new File("file.txt");
  
        try {
            FileInputStream input
                = new FileInputStream(file);
            int character;
            // read character by character by default
            // read() function return int between
            // 0 and 255.
  
            while ((character = input.read()) != -1) {
                System.out.print((char)character);
            }
  
            input.close();
            System.out.println("File is Closed");
            System.out.println(
                "Now we will again try to read");
            while ((character = input.read()) != -1) {
                System.out.print((char)character);
            }
        }
        catch (Exception e) {
            System.out.println(
                "File is closed. Cannot be read");
            e.printStackTrace();
        }
    }
}

Output

GeeksforGeeks is a computer science portal
File is Closed
Now we will again try to read
File is closed. Cannot be read
java.io.IOException: Stream Closed
       at java.base/java.io.FileInputStream.read0(Native Method)
       at java.base/java.io.FileInputStream.read(Unknown Source)
       at abc.main(abc.java:28)

Note: This code will not run on an online IDE as it requires a file on the system.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!