PUBLISHED ON: FEBRUARY 26, 2021
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.