Signup/Sign In

Java InputStreamReader close() Method

In this tutorial, we will learn about the close() method, of the InputStreamReader class in Java. This work of this method is to close the InputStreamReader instance. After this method is invoked, the operation of read(), ready(), mark(), reset(), or skip() methods on the stream will throw an IOException.

Syntax

This is the syntax declaration of this method. It does not accept any parameter, neither does it return any value.

public void close()

Example: Close InputStreamReader instance in Java

In this example, we are closing the stream using the close() method once we read the data from the file using InputStreamReader so it will work without any error. We close the stream to remove the resources linked with it.

import java.io.FileInputStream;
import java.io.InputStreamReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		int i;
		char c;
		try
		{
			FileInputStream	fileInputStream = new FileInputStream("E://studytonight//output.txt");
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			i = inputStreamReader.read();
			c = (char)i;
			System.out.println(c);
			inputStreamReader.close();
			System.out.println("close() invoked");
		}
		catch (Exception e) 
		{
			System.out.print("Error: "+e.toString());
		} 
	}
}


H
close() invoked

output.txt

Hello Studytonight

Example 2: Close InputStream instance in Java

In this example, we are closing the stream before reading the data from it so all the resources related to it will be removed. If we try to read the data after closing the stream it will throw an exception java.io.IOException: Stream closed.

import java.io.FileInputStream;
import java.io.InputStreamReader;
public class StudyTonight 
{
	public static void main(String args[])
	{
		int i;
		char c;
		try
		{
			FileInputStream	fileInputStream = new FileInputStream("E://studytonight//output.txt");
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			inputStreamReader.close();
			System.out.println("close() invoked");
			i = inputStreamReader.read();
			c = (char)i;
			System.out.println(c);
		}
		catch (Exception e) 
		{
			System.out.print("Error: "+e.toString());
		} 
	}
}


close() invoked
Error: java.io.IOException: Stream closed

output.txt

Hello Studytonight

Conclusion

In this tutorial, we learned about the close() method of the InputStreamReader class in Java. This method, when called, will close the current stream and no further operation can be performed on it.



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.