Signup/Sign In

StringWriter close() method in Java

In this tutorial, we will learn about the close() method of StringWriter class in Java. This method is used to close this StringWriter stream. When we call any of its methods after closing the stream will not result from an exception. This method is available in the java.io package. Closing a writer deallocates any value in it or any resources associated with it.

Syntax

This is the syntax declaration of a close() method, It does not accept any parameter and the return type of the method is void, it returns nothing.

public void close()

Example 1

Here, in this example, we will implement the close() method, once we create the writer we perform the work and then call the close() method to deallocate the corresponding resources related to the writer. When we call any of its methods after closing the stream will not result from an exception.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		String str = "Hello Studytonight"; 
		try
		{ 
			StringWriter writer = new StringWriter(); 
			writer.write(str); 
			
			System.out.println(writer.toString()); 

			writer.close(); 
		} 
		catch (Exception e)
		{ 
			System.out.println(e); 
		} 
	} 
}


Hello Studytonight

Example 2

Here, we are implementing the close() method, in this example firstly we have written data to the writer using the write() method and then we are calling the close() method to deallocate the resources, when we call any of its methods after closing the stream will not result from an exception.

import java.io.IOException;
import java.io.StringWriter;
class StudyTonight
{
	public static void main(String[] args) throws IOException 
	{ 
		try 
		{ 
			StringWriter writer = new StringWriter(); 
			writer.write(65); 
			System.out.println(writer.toString()); 

			writer.close(); 
		} 
		catch (Exception e) 
		{ 
			System.out.println(e); 
		} 
	} 
}


A

Conclusion

In this example, we learned about the close() method, This method is used to close this StringWriter stream. When we call any of its methods after closing the stream will not result from an exception. This method is available in the java.io package.



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.