tags:

views:

114

answers:

3

If I just call close() in a output stream, the output is guaranteed, or need I call flush() always?

+6  A: 

Close() always flushes so no need to call.

ZZ Coder
A: 

Streams represent resources which you must always clean up explicitly, by calling the close method. Some java.io classes (apparently just the output classes) include a flush method. When a close method is called on a such a class, it automatically performs a flush. There is no need to explicitly call flush before calling close.

giri
A: 

Whilst close should call flush, it's a bit more complicated than that...

Firstly, decorators (such as BufferedOutputStream) are common in Java. Construction of the decorator may fail, so you need to close the "raw" stream in a finally block whose try includes the decorator. In the case of an exception, you don't usually need to close the decorator (except, for instance, for badly implemented compression decorators). You do typically need to flush the decorator in the non-exception case. Therefore:

final RawOutputStream rawOut = new RawOutputStream(rawThing);
try {
    final DecoratedOutputStream out = new DecoratedOutputStream(rawOut);
    // ... stuff with out within ...
    out.flush();
} finally {
    rawOut.close();
}

To top it, decorator close methods are often implemented incorrectly. That includes some in java.io until recently.

Of course, you probably want to use the Execute Around idiom to keep in DRY(ish).

Tom Hawtin - tackline