Java FileWriter flush() Method
Example
See the file size before and after the writer is flushed:
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");
FileWriter myWriter = new FileWriter(myFile);
myWriter.write("Hello World");
System.out.println(myFile.length());
myWriter.flush();
System.out.println(myFile.length());
myWriter.close();
}
}
Definition and Usage
The flush() method writes all characters that are waiting in memory to the file right away.
A FileWriter keeps some text in a buffer (a block of memory that holds text before it goes to the file), and writes it to the file later. 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
❮ FileWriter Methods