FilterOutputStream 是輸出流的裝飾者基類,採用裝飾器模式「包裝」其他 OutputStream,為其動態添加功能。其核心子類包括:
writeInt、writeUTF)。public class FilterOutputStream extends OutputStream {
protected OutputStream out; // 被裝飾的目標流
public FilterOutputStream(OutputStream out) {
this.out = out;
}
// 所有寫入操作委託給 out
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 {
// 參數校驗後逐字節調用 write(int)
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();
}
}
關鍵點:
write(byte[], int, int) 默認實現逐字節委託,子類(如 BufferedOutputStream)通常會重寫以批量寫入提升性能。close() 先 flush() 再關閉底層流,捕獲 flush 異常防止資源洩漏。// 鏈式裝飾:文件 -> 緩衝 -> 數據類型寫入
try (DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream("data.bin")))) {
dos.writeUTF("Hello");
dos.writeInt(2024);
dos.writeDouble(3.14159);
}
此鏈路中,FileOutputStream 負責落盤,BufferedOutputStream 批量刷新,DataOutputStream 編碼基本類型,各司其職。
FilterOutputStream 以極簡的委託實現奠定了輸出流擴展的基石。理解其「透傳」本質,有助於正確構建流鏈路、排查寫入阻塞、數據截斷等問題。