June 30, 2008

Working with OutputStreams

I'm a big fan of the implementations of OutputStreams in Java - a very good example of the decorator pattern. It is great to be able to add capabilities by simple composition.

I'm using various OutputStream implementations to create an API to encrypt files within a Zip file. Unfortunately there are some maddening inconsistencies.

The one that is giving me the biggest headache is the fact that the CipherOutputStream close method closes the underlying output stream. With any other OutputStream implementation one would call the flush method, but for block ciphers, the block is not flushed until close is called. If one is encrypting multiple files to the underlying stream one has to work out some way to close the CipherOutputStream without closing the underlying stream.

What is even more maddening is the fact that DeflaterOutputStream has a method called finish that does exactly what I would need, it completes the deflation without closing the underlying stream.

Why can't CipherOutputStream have a similar method?