Java BufferedWriter close() Method
Example
Write text to a file, close the writer, and read the text back:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt"));
bw.write("Hello World");
bw.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println(br.readLine());
br.close();
}
}
Definition and Usage
The close() method closes the writer. First, it writes all text that is still in the buffer (a block of memory that holds text before it goes to the file) to the file. It also closes the FileWriter inside it.
After you close a writer, you cannot write to it anymore. Methods like write() then throw an IOException.
Tip: Use try-with-resources to close the writer automatically, even if an error occurs.
Syntax
public void close()
Parameter Values
None.
Related Pages
❮ BufferedWriter Methods