Share on Google+Share on Google+

Java file flush

This section demonstrates you the use of method flush().

Java file flush

This section demonstrates you the use of method flush().

Description of code:

Stream represents resource so it is necessary to flush out the stream after performing any file operation before exiting the program otherwise you could lose buffered data. You can use flush() or close() method for this purpose.

In the given example, we have used BufferedWriter class along with FileWriter class to write some text to the file. Then using the method write() of BufferedWriter class, we have written the text into the file. Now in order to keep the data safe, we have used flush() method. This method forced the buffered data out of an output stream.

Here is the code:


public class FileFlush {
	public static void main(String[] args) throws Exception {
		String st = "Hello";
		File f = new File("C:/hello.txt");
		BufferedWriter bw = new BufferedWriter(new FileWriter(f));

Through the method flush(), you can flush out any output stream and keep your data safe.


Posted on: April 14, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.