Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flush() before close()

Tags:

java

iostream

As per the java docs, invoking close() on any java.io Streams automatically invokes flush(). But I have seen in lot of examples, even in production codes, developers have explicitly used flush() just before close(). In what conditions we need to use flush() just before close()?

like image 454
Sivasubramaniam Arunachalam Avatar asked Mar 25 '12 07:03

Sivasubramaniam Arunachalam


People also ask

Does Close also flush?

Its close() method does NOT call flush() .

What are flush () and close () used for?

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream. But close() closes the stream permanently.

When should you flush a stream?

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() .

What does flush () do in Java?

flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it.


2 Answers

Developer get into a habit of calling flush() after writing something which must be sent.

IMHO Using flush() then close() is common when there has just been a write e.g.

// write a message out.write(buffer, 0, size); out.flush();  // finished out.close(); 

As you can see the flush() is redundant, but means you are following a pattern.

like image 157
Peter Lawrey Avatar answered Oct 19 '22 17:10

Peter Lawrey


I guess in many cases it's because they don't know close() also invokes flush(), so they want to be safe.

Anyway, using a buffered stream should make manual flushing almost redundant.

like image 39
Bozho Avatar answered Oct 19 '22 18:10

Bozho