Open In App

Java FileReader Class close() Method with Examples

Last Updated : 16 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The close() method of FileReader class in Java is used to close the file reader. We can’t utilize the reader to read data after the close() method is executed. This procedure closes the stream and frees all associated system resources. Calling read(), ready(), mark(), reset(), or skip() after this method has been used will result in an IOException.

Syntax:

public abstract void close()

There are no parameters or values returned by this procedure.

Example 1: We verify whether the stream implements the mark() function, and after the stream’s activities are complete, we use the close() method to free up all the resources tied to or temporarily allocated for the stream; beyond this point, we can no longer utilize it.

Java




// Java Program to demonstrate the working of close() 
// method of FileReader class in Java
  
import java.io.FileReader;
  
public class GFG {
    public static void main(String args[])
    {
        try {
            FileReader fileReader = new FileReader(
                "C:\\Users\\lenovo\\Desktop\\input.txt");
            int i;
            while ((i = fileReader.read()) != -1)
                System.out.print((char)i);
            fileReader.close();
        }
        catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}


input.txt has the following text

Output:

Example 2: When we try to utilize it, an exception like this is thrown because all of the resources necessary for the current stream have been de-allocated.

Java




// Java Program to demonstrate the working of close() 
// method of FileReader class in Java
  
import java.io.FileReader;
  
public class GFG {
    public static void main(String args[])
    {
        try {
            FileReader fileReader = new FileReader(
                "C:\\Users\\lenovo\\Desktop\\input.txt");
            int i;
            fileReader.close();
            while ((i = fileReader.read()) != -1)
                System.out.print((char)i);
        }
        catch (Exception e) {
            System.out.println("Error: " + e.toString());
        }
    }
}


Output: Any other operation on the stream is invalidated when this method is called.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads