FilterInputStream、FilterOutputStream是过滤器字节输入输出流。它们的主要用途在于封装其他的输入输出流,为它们提供一些额外的功能。
FilterInputStream
package java.io;
public class FilterInputStream extends InputStream {
//要过滤进行额外操作的InputStream对象
protected volatile InputStream in;
//当我们在创建FilterInputStream实例时需要传入一个InputStream子类的实例。
//在FilterInputStream的方法中就是调用的传入的InputStream子类的方法
protected FilterInputStream(InputStream in) {
this.in = in;
}
public int read() throws IOException {
return in.read();
}
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
public int read(byte b[], int off, int len) throws IOException {
return in.read(b, off, len);
}
public long skip(long n) throws IOException {
return in.skip(n);
}
public int available() throws IOException {
return in.available();
}
public void close() throws IOException {
in.close();
}
public synchronized void mark(int readlimit) {
in.mark(readlimit);
}
public synchronized void reset() throws IOException {
in.reset();
}
public boolean markSupported() {
return in.markSupported();
}
}
从FilterInputStream的源码中可以看到,它本身只是简单地重写那些将所有请求传递给所包含输入流的InputStream所有方法。也就是说FilterInputStream并没有提供什么装饰功能。
FilterInputStream的子类可进一步重写这些方法中的一些方法,来提供装饰功能。它的常用的子类有BufferedInputStream和DataInputStream。比如,BufferedInputStream的作用就是为它装饰的输入流提供缓冲功能。
总结
- FilterInputStream、FilterOutputStream是过滤器字节输入输出流。它们的主要用途在于封装其他的输入输出流,为它们提供一些额外的功能。
- FilterInputStream、FilterOutputStream并没有提供什么装饰功能。FilterInputStream、FilterOutputStream的子类可进一步重写这些方法中的一些方法,来提供装饰功能。
- FilterInputStream装饰功能的实现的关键在于类中有一个InputStream字段,依赖这个字段它才可以对InputStream的子类提供装饰功能。FilterOutputStream也是如此。