Signup/Sign In

Java FileReader close() Method

In this tutorial, we will learn about the close() method of the FileReader class in Java. This method closes the stream and releases all the system resources linked with it. Once this method is invocated, the calling of read(), ready(), mark(), reset(), or skip() will throw an IOException.

Syntax

This method does not accept any parameter or return any value.

public abstract void close()

Example 1: Close FileReader Instance

In this example, we have created a FilterReader stream to read the data, in this particular case we are checking if the stream supports the mark() method or not, once the operations related to the stream are completed we call the close() method to free up all the resources linked or currently allocated for the stream, after this point we cannot use this stream.

import java.io.FileReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{   		
			FileReader fileReader=new FileReader("E:\\studytonight\\output.txt");    
			int i;    
			while((i=fileReader.read())!=-1)    
				System.out.print((char)i);    
			fileReader.close();    
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e.toString());
		}
	}
}

Welcome to Studytonight

output.txt

Welcome to Studytonight

Example 1: Close FileReader Instance

Here is the example when we close the current stream and afterward we try to use it then it will throw an exception like this because all the resources required for the current stream are de-allocated.

import java.io.FilterReader;
import java.io.Reader;
import java.io.StringReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		try
		{
			Reader reader = new StringReader("Hello Studeytonight"); 
			int i;
			FilterReader filterReader = new FilterReader(reader) {};
			filterReader.close(); 
			
			while ((i = filterReader.read()) != -1) {
				char  c = (char) i;
				System.out.print(c);
			}
		}
		catch(Exception e)
		{
			System.out.print("Error: "+e.toString());
		}
	} 
}


Error: java.io.IOException: Stream closed

Conclusion

In this tutorial, we learned about the close() method of the FileReader class in Java, which closes the stream and releases all the resources associated with the system stream. Calling of this method invalidates any other operation on the stream.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.