Signup/Sign In

Java CharArrayReader close() Method

In this tutorial, we will learn about the close() method of the CharArrayReader class in Java. This method is used to close the character array reader and immediately release all the resources attached to it in the stream. Calling of any operation, including read (), ready (), mark (), reset (), or skip () method, after the close() method is called, will throw an IOException.

Syntax

Following is the syntax of this method, no parameter is required and no value is returned by it.

public void close()

Example: Close Reader in Java using close() Method

In this example, we are demonstrating the use of close() method, when we read the data from the stream we close that stream using the close() method. After calling this all the resources associated with the stream get released and we cannot use stream after this.

import java.io.CharArrayReader;
import java.io.IOException;
class StudyTonight
{
	public static void main(String[] args)  
	{ 
		CharArrayReader charArrayReader = null;  
		char[] arr = {'H', 'E', 'L', 'L', 'O'};  
		try 
		{  
			charArrayReader = new CharArrayReader(arr);  
			char c = (char)charArrayReader.read();  
			System.out.println(c);
			charArrayReader.close();  
		} 
		catch(IOException e) 
		{  
			System.out.print("Error: "+e.toString());  
		} 
	} 
}


H

Example 2: Close Reader in Java using close() Method

Here we will see what happens when trying to read the data after closing the stream, when we try to read from the stream that is already closed and no resources associated with it then it will cause an exception saying : Error: java.io.IOException: Stream closed and that is the reason we should not close it before the reading.

import java.io.CharArrayReader;
import java.io.IOException;
class StudyTonight
{
	public static void main(String[] args)  
	{ 
		CharArrayReader charArrayReader = null;  
		char[] arr = {'H', 'E', 'L', 'L', 'O'};  
		try 
		{  
			charArrayReader = new CharArrayReader(arr);  
			charArrayReader.close();  
			char c = (char)charArrayReader.read();  
			System.out.println(c);		
		} 
		catch(IOException e) 
		{  
			System.out.print("Error: "+e.toString());  
		} 
	} 
}


Error: java.io.IOException: Stream closed

Conclusion:

In this tutorial, we learned about close() method of the CharArrayReader class in Java, which closes the stream and releases all the associated resources, after which any operation on stream raises an IOException.



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.