一、FilterInputStream介绍
/**
* A <code>FilterInputStream</code> contains
* some other input stream, which it uses as
* its basic source of data, possibly transforming
* the data along the way or providing additional
* functionality. The class <code>FilterInputStream</code>
* itself simply overrides all methods of
* <code>InputStream</code> with versions that
* pass all requests to the contained input
* stream. Subclasses of <code>FilterInputStream</code>
* may further override some of these methods
* and may also provide additional methods
* and fields.
*
* @author Jonathan Payne
* @since JDK1.0
*/
public class FilterInputStream extends InputStream
由源码中对该类的注释我们可以知道这个类的内部包含其他的输入流成员变量,这个输入流主要用来保存它的基础数据源。该类重写了所有InputStream方法并在方法内部交由成员变量中的基础数据源输入流in去处理,它的作用简单概括就是“封装了其他的数据输入流,供子类扩展他们提供额外的功能”,很容易我们可以想到其中应用了装饰器设计模式思想。
二、FilterInputStream源码分析
package java.io;
public class FilterInputStream extends InputStream {
protected volatile InputStream in;
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类内部引用了一个输入流对象in,各个成员方法只是在方法内部调用了流对象in相应的方法并未做其他处理,FilterInputStream子类封装了其他的输入流并重写了部分方法为输入流提供额外的功能。
三、常用子类
BufferedInputStream
DataInputStream