简体   繁体   中英

Can I close underlying outputstream and let the decorator BufferedOutputStream unclosed

I have multiple implementations of a

 void convert(List< InputStream > list, OutputStream os)

method.

The given resources may be reused and are so not released by the method implementations. However I would like to decorate the given output stream with a BufferedOutputStream in some cases.

Closing the decorator will result in closing the underlying stream which I want to avoid.

My question is so : Can I safely let the decorator unclosed and let the calling method manage the underlying stream release ?

Decorating classes usually do not open system resources (like an operating system file-handle) that must be closed to prevent resource leakage. The given OutputStream parameter must be closed (because it is probably associated with an open system resource), but as you mention, this is the responsibility of the caller.

But if you do not close the decorating class, you must take care of method calls that normally take place in the close() method. In case of BufferedOutputStream you can see that flush() is called in the super class FilterOutputStream close() method.

To accommodate these missing method calls, create a separate NonClosingBufferedOutputStream class that extends BufferedOutputStream that contains a modified version of the close() method from the FilterOutputStream (simply comment out the line out.close(); ). You can now use this class as a normal Closeable and avoid warnings from your IDE/compiler.

I was going to recommend using the CloseShieldOutputStream from Apache commons-io, but looking at the source code , it appears that flush() is not called in the close() method. Despite this shortcoming, replacing the underlying outputstream with a ClosedOutputStream does appear to be a good idea: it will show programming mistakes much sooner.

Note that for other decorating classes like the GZIPOutputStream , other methods besides flush() could be appropriate. In GZIPOutputStream 's case, creating a NonClosingGZIPOutputStream class with a modified close() method that calls finish() could do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM