Java FileWriter close() Method
Example
Close a writer, and see that it cannot be used after that:
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Hello World");
myWriter.close();
try {
myWriter.write("More text");
} catch (IOException e) {
System.out.println("Error: the writer is closed.");
}
}
}
Definition and Usage
The close() method writes any text that is still waiting in memory to the file, and then closes the writer. This releases the file (other programs can use it again).
After you close a writer, you cannot write to it anymore. Methods like write() then throw an IOException, like in the example.
Tip: Use try-with-resources to close the writer automatically, even if an error occurs.
Syntax
public void close()
Parameter Values
None.
Related Pages
❮ FileWriter Methods