Home Tutorial Java Core Files Java file flush

 
 

Java file flush
Posted on: April 14, 2006 at 12:00 AM
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:

import java.io.*;

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));
		bw.write(st);
		bw.flush();
	}
}

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

Related Tags for Java file flush:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.