Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of FilterOutputStream

What is practical usage of FilterOutputStream in Java? From javadocs:

This class is the superclass of all classes that filter output streams. These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality.

For me it seems to have same methods as OutputStream (maybe it overrides them for some reason?). What kind of data "transformation" does it offer and when can one use it in own Java application?

like image 433
user35443 Avatar asked Dec 06 '22 06:12

user35443


2 Answers

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.

like image 172
Evgeniy Dorofeev Avatar answered Dec 25 '22 04:12

Evgeniy Dorofeev


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

like image 30
Kayaman Avatar answered Dec 25 '22 03:12

Kayaman