首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java IO 基石:FilterInputStream 過濾輸入流架構解析

     編輯:Java 相關知識

FilterInputStream 核心定位

FilterInputStream 是輸入流的裝飾者基類,同樣採用裝飾器模式包裝 InputStream。主要子類:

  • BufferedInputStream:讀取緩衝 + 標記重置。
  • DataInputStream:機器無關地讀取基本類型(配合 DataOutputStream 使用)。

源碼核心實現(JDK 1.7)

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(); }
}

設計亮點:

  1. in 字段聲明 volatile,確保多線程環境下引用可見性。
  2. 方法均為單行委託,零業務邏輯,極薄封裝層。
  3. 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 以「零邏輯委託」實現了輸入流功能的正交擴展。掌握其透傳機制,能避免重複造輪子,並在組合流時正確排序裝飾器順序(緩衝在外,功能在內)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved