Java file flush


 

Java file flush

This section demonstrates you the use of method 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:

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.

Ads