[java] What is the purpose of flush() in Java streams?

In Java, flush() method is used in streams. But I don't understand what are all the purpose of using this method?

fin.flush();

tell me some suggestions.

This question is related to java flush stream

The answer is


If the buffer is full, all strings that is buffered on it, they will be saved onto the disk. Buffers is used for avoiding from Big Deals! and overhead.

In BufferedWriter class that is placed in java libs, there is a one line like:

private static int defaultCharBufferSize = 8192;

If you do want to send data before the buffer is full, you do have control. Just Flush It. Calls to writer.flush() say, "send whatever's in the buffer, now!

reference book: https://www.amazon.com/Head-First-Java-Kathy-Sierra/dp/0596009208

pages:453


When you write data to a stream, it is not written immediately, and it is buffered. So use flush() when you need to be sure that all your data from buffer is written.

We need to be sure that all the writes are completed before we close the stream, and that is why flush() is called in file/buffered writer's close().

But if you have a requirement that all your writes be saved anytime before you close the stream, use flush().


For performance issue, first data is to be written into Buffer. When buffer get full then data is written to output (File,console etc.). When buffer is partially filled and you want to send it to output(file,console) then you need to call flush() method manually in order to write partially filled buffer to output(file,console).


Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.


When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand


In addition to other good answers here, this explanation made things crystal clear for me:

A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. monitor) when the buffer is full or meets a certain number of characters. This can cause your system to lag if you just have a few characters to send to an output device. The flush() method will immediately flush the contents of the buffer to the output stream.

Source: https://www.youtube.com/watch?v=MjK3dZTc0Lg