Usage of FilterOutputStream

感情迁移 提交于 2019-12-04 12:22:32

Joshua Bloch in Effective Java Item 16: Favor composition over inheritance explains why inheritance is not always the best tool for the job. It is often more efficient to use Decorator pattern. FilterOutputStream and FilterInputStream are the base for implementing this pattern. For example I want to block OutputStream.close. This is what I could do

class NonCloseableOutputStream extends FilterOutputStream {

    public NonCloseableOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void close() throws IOException {
        // ignore
    }
}

Now my class can accept any subclass of OutputStream and make it non-closeable.

Kayaman

The class FilterOutputStream itself simply overrides all methods of OutputStream with versions that pass all requests to the underlying output stream.

So as you suspected, it doesn't do much besides overrides the methods with a somewhat more useful implementation.

These classes are from Java 1.0, so they may not be designed in the best possible way. However, extending a FilterStream will still work just fine, in case you need to create your own (although there are ready-made filter streams (like CheckedInputStream, DigestInputStream or CipherInputStream) for plenty of things).

It has the same methods as OutputStream, since it extends OutputStream. In fact, that is a very useful feature: you can supply a FilterOutputStream anywhere an OutputStream is expected.

By default, a FilterOutputStream does not offer you any added functionality. As its Javadoc states:

Subclasses of FilterOutputStream may further override some of these methods

For example, you could extend FilterOutputStream and override the write(int b) method in a way that it writes any byte you supply to it, except 13 or 10. That way, you would have an outputstream that never contains newlines. It may not be of any use, but its just an example.

William Morrison

CheckedInputStream looked useful to me. It calculates a checksum based on data passed through it. I could see myself using that.

Another example is the DeflateOutputStream which handles compressing data formatted correctly, automatically.

I think you understand exactly what it's used for. Subclasses just manipulate data before forwarding it on to the underlying stream.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!