views:

157

answers:

2

Why does the filter stream used and where? I read that filter streams will be used for letting the needed information into the stream.. Is that right and if so how we can filter from the stream and where exactly it will be used??

java.io.Filter....

My problem here is its very hard to understand why we are using the Filter streams, Since we can do most of the stuffs using other streams, right.

+3  A: 

I suppose you are talking about java.io.Filter* (like FilterInputStream).

If we talk about the FilterInputStream class, it is simply a wrapper around an InputStream that does nothing. Every call to a method of the Filter will simply call the corresponding method on the wrapped InputStream. Alone, it is quite useless.

Imagine that you want an InputStream that transforms every "a" character into a "b". You could extend FilterInputStream and override the read() methods :

// this code has not been tested
class ABFilter extends FilterInputStream {
    public ABFilter (InputStream in) {
        super(in);
    }
    @Override
    public int read() {
        int character = super.read();
        if (character == 97)
            return 98;
        return character;
    }
    // similarly implement all other "read()" methods
}

Now you can use this stream to wrap any existing stream :

InputStream streamWithA = ...;
InputStream streamWithoutA = new FilterInputStream(streamWithA);
Guillaume
Could you please be in detail.. thanks
i2ijeya
Thanks... understood how filtering is done.. So what does the subclasses do. ie.,it has four derived classes and what is the purpose of those classes being the sub class of FilterInputStream??
i2ijeya
Since FilterInputStream doesn't have any 0 argument constructor, how could we extend it with another class???
i2ijeya
+2  A: 

These Filter* classes are needed to be able to extend classes at run-time without knowing underlying type. This pattern is called Decorator or Wrapper,

http://en.wikipedia.org/wiki/Decorator%5Fpattern

Take BufferedInputStream as example. Without wrapper, you would need multiple versions for each InputStream. For example,

  BufferedInputStream extends InputStream ...
  BufferedFileInputStream extends FileInputStream ...
  BufferedByteArrayInputStream extends ByteArrayInputStream ...

Now with the wrapper, all you need is

  BufferedInputStream extends FilterInputStream ...
ZZ Coder