FilterOutputStream
应用组合模式,它将所有调用委托给其实例变量out
:
/* The underlying output stream to be filtered. */
protected OutputStream out;
FilterOutputStream
也有抽象类的默认实现OutputStream
:
public void write(int b) throws IOException {
out.write(b);
}
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len) throws IOException {
if ((off | len | (b.length - (len + off)) | (off + len)) < 0)
throw new IndexOutOfBoundsException();
for (int i = 0 ; i < len ; i++) {
write(b[off + i]);
}
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
try {
flush();
} catch (IOException ignored) {
}
out.close();
}
现在,包括在内的任何类PrintStream
都可以扩展FilterOutputStream
和覆盖适当的方法。请注意,他们仍然需要将呼叫委托给out
. 例如PrintStream#flush()
:
public void flush() {
synchronized (this) {
try {
ensureOpen();
out.flush();
}
catch (IOException x) {
trouble = true;
}
}
}