Java FileOutputStream flush() Method
Example
Write text and flush the stream, then read the file while the stream is still open:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
FileOutputStream output = new FileOutputStream("filename.txt");
output.write("Hello World".getBytes());
output.flush();
Scanner reader = new Scanner(new File("filename.txt"));
System.out.println(reader.nextLine());
reader.close();
output.close();
}
}
Definition and Usage
The flush() method forces any buffered bytes (bytes that wait in memory) to be written to the file.
FileOutputStream has no buffer of its own. It writes the bytes to the file right away, so flush() does nothing for this class. It is important for buffered streams, like BufferedOutputStream, which keep bytes in memory before they write them.
Syntax
public void flush()
Parameter Values
None.
Technical Details
| Throws: | IOException - if the bytes cannot be written. |
|---|
Related Pages
Java FileOutputStream Tutorial
❮ FileOutputStream Methods