Java BufferedWriter flush() Method
Example
See the file size before and after the writer is flushed:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File myFile = new File("filename.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(myFile));
bw.write("Hello World");
System.out.println(myFile.length());
bw.flush();
System.out.println(myFile.length());
bw.close();
}
}
Definition and Usage
The flush() method writes all text that is waiting in the buffer (a block of memory that holds text before it goes to the file) to the file right away.
A BufferedWriter collects text in its buffer and writes it to the file in bigger blocks, which is faster. Use flush() when the text must be in the file now, but you want to keep the writer open.
Note: close() also flushes the writer, so you do not need to call flush() before close().
Syntax
public void flush()
Parameter Values
None.
Technical Details
| Throws: | IOException - if the writer is closed, or if another I/O error occurs. |
|---|
Related Pages
❮ BufferedWriter Methods