Java IO流基礎分析與學習

java io流類圖

IO架構介紹:

        IO分爲字節流和字符流處理2種類型,有對應的輸入與輸出流來處理文件的讀寫操作

       輸入與輸出流處理的結構類似,基本上輸入流(input)與輸出流(output)包含對 byte ,String , file 文件的讀寫操作

 

設計模式介紹:

        java IO流使用了裝飾器模式和適配器模式

裝飾器模式:

        對現有的對象添加新的功能,同時又不改變其結構。它是作爲現有的類的一個包裝類。

        java中FilterInputStream, FilterReader等都使用裏裝飾器模式,FilterInputStream實現抽象,子類根據不同的需求實現不同功能的實現;

        如BufferedInputStream是對IO讀的操作添加了緩存大小

如下列源碼:

       BufferedInputStream需要傳遞父類對象,根據設定的緩存區大小進行讀的操作

 

public BufferedInputStream(InputStream in, int size) {
    super(in);
    if (size <= 0) {
        throw new IllegalArgumentException("Buffer size <= 0");
    }
    buf = new byte[size];
}

適配器模式:

        作爲兩個不兼容的接口之間的橋樑。

        java調用中在不改變 A調用和B返回的情況下 新增一個C的接口進行適配A調用B的方式;

        即是A調用C,C來重新組裝對B的請求來實現調用B接口,最後在組裝A的返回數據以適應A的接口;

        IO裏面的應用:

           StringBufferInputStream ,ByteArrayInputStream等都是對inputStream的適配,把字節流的讀取適配成byte數組或者String的讀取

   如下ByteArrayInputStream源碼結構,ByteArrayInputStream裏面定義了一個數組類型,用來接收所有預讀的byte數組類型對象,在使用read同步方法進行模擬inputStream讀取

 

public class ByteArrayInputStream extends InputStream {

    protected byte buf[];

    protected int pos;

    protected int mark = 0;

    protected int count;

    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }
    public ByteArrayInputStream(byte buf[], int offset, int length) {
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.mark = offset;
    }
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
    public synchronized int read(byte b[], int off, int len) {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        }
        if (pos >= count) {
            return -1;
        }
        int avail = count - pos;
        if (len > avail) {
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        System.arraycopy(buf, pos, b, off, len);
        pos += len;
        return len;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章