PUBLISHED ON: MARCH 4, 2021
Java FileWriter close() Method
In this tutorial, we will learn about the close()
method of FileWriter class in Java. This method is used to close this FileWriter 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: Close FileWriter
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.FileWriter;
import java.io.IOException;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt");
String str = "Hello Studytonight";
fileWriter.write(str);
fileWriter.close();
System.out.println("Data Written to the file successfully");
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Data Written to the file successfully
output.txt
Hello Studytonight
Example: Close FileWriter Instance
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.FileWriter;
import java.io.IOException;
class StudyTonight
{
public static void main(String[] args) throws IOException
{
try
{
FileWriter fileWriter=new FileWriter("E:\\studytonight\\output.txt");
char c='A';
fileWriter.write(c);
fileWriter.close();
System.out.println("Data Written to the file successfully");
}
catch(Exception e)
{
System.out.println("Error: "+e.toString());
}
}
}
Data Written to the file successfully
output.txt
A
Conclusion
In this example, we learned about the close() method, This method is used to close this FileWriter 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.