FilterInputStream 是輸入流的裝飾者基類,同樣採用裝飾器模式包裝 InputStream。主要子類:
DataOutputStream 使用)。public class FilterInputStream extends InputStream {
protected volatile InputStream in; // volatile 保證多線程可見性
protected FilterInputStream(InputStream in) { this.in = 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(); }
}
設計亮點:
in 字段聲明 volatile,確保多線程環境下引用可見性。mark/reset 直接透傳,能否標記完全取決於底層流實現。// 文件 -> 緩衝 -> 基本類型讀取
try (DataInputStream dis = new DataInputStream(
new BufferedInputStream(
new FileInputStream("data.bin")))) {
String str = dis.readUTF();
int num = dis.readInt();
double d = dis.readDouble();
}
注意:DataInputStream 本身不提供緩衡,必須外層包裹 BufferedInputStream 才能獲得高效讀取。
FilterInputStream 以「零邏輯委託」實現了輸入流功能的正交擴展。掌握其透傳機制,能避免重複造輪子,並在組合流時正確排序裝飾器順序(緩衝在外,功能在內)。