基本概念
FilterInputStream / FilterOutputStream (过滤输出流/过滤输入流)这两个类分别继承自 Inpustream 与 OutputStream ,提供的作用 “封装其它的输入流,并为它们提供额外的功能“。
FilterInputStream和FilterOutputStream 本身并没给出其它额外的功能实现,只是做了一层简单地封装,实现额外功能的实际是它们的子类。这也正是装饰者模式的应用。
源码分析
1.FilterInputStream
类结构图
成员变量
//代表要操作的流
protected volatile InputStream in;
构造函数
// 将流赋于成员变量 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();
}
}
2.FilterOutputStream
结构图
成员变量
// 表示要过滤的输出流
protected OutputStream out;
构造函数
// 将流赋于成员变量 out,说明操作的并不是输出流本身
public FilterOutputStream(OutputStream out) {
this.out = out;
}
writer 方法,与 FilterInputstream 不同,它并不是全部调用流本身的 writer 方法。
① 通过调用要过滤的输出流本身的方法。
②③ 在本类中定义,具体的实现关系如 ② -> ③ -> ①
// ①写入单个字符
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 {
// 关键 -> 执行 close 之前会调用 flush
flush();
} catch (IOException ignored) {
}
out.close();
}