Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Okio 簡化 I/O:Source、Sink 與 Buffer 的設計之美

編輯:關於 Android 開發

Okio 是 Square 開發的函式庫,它補足了 java.io 與 java.nio 的不足,讓「讀取、儲存、處理資料」這件事變得更方便、更快速。OkHttp 的底層正是以它作為 I/O 基礎。在開發中適度使用,能省下大量樣板程式碼。

一、基本資訊與核心抽象

目前 Okio 的最新版本是 1.6.0,Gradle 引用方式:

compile 'com.squareup.okio:okio:1.6.0'

Okio 有兩個關鍵介面:Sink 與 Source,兩者都繼承自 Closeable。可以粗略地這樣理解:

  • Sink ≈ OutputStream(寫出)
  • Source ≈ InputStream(讀入)

而且這兩者都支援讀寫超時設定,這在網路 I/O 場景中是刚需。

二、家族結構

圍繞這兩個介面,Okio 展開了一組職責清晰的實作:

  • BufferedSink / BufferedSource:具備緩衝區的子介面,實作分別為 RealBufferedSink 與 RealBufferedSource。
  • GzipSink / GzipSource:支援 gzip 壓縮的實作。
  • ForwardingSink / ForwardingSource:抽象類,提供「委派」能力,方便你在不改動原物件的前提下包裝一層自訂行為。
  • DeflaterSink / InflaterSource:壓縮與解壓縮的底層實作,為 GzipSink 與 GzipSource 服務。

三、BufferedSink 與 BufferedSource 的對稱設計

BufferedSink 定義了一系列寫入緩衝區的方法:write() 寫 byte 陣列、writeUtf8() 寫字串,還有一整組 writeByte、writeShort、writeInt、writeLong、writeDecimalLong 等。

BufferedSource 的方法與它幾乎一一對應,只是方向相反:readUtf8()、readByte()、readShort()、readInt()、readLong()……

這種高度對稱的 API 設計是 Okio 易用的關鍵:讀與寫的心智模型完全一致,學會一邊就等於學會另一邊。

四、RealBufferedSink 的實作手法

RealBufferedSink 與 RealBufferedSource 都是透過「包裝一個 Sink + Buffer」或「Source + Buffer」來實作的。

以 RealBufferedSink 為例,它對外暴露的 writeXxx() 系列方法,實際操作的都是成員變數 buffer,寫入完成後再呼叫一個方法把 buffer 的內容刷進真正的 sink:

public BufferedSink writeLong(long v) throws IOException {
    if (this.closed) {
        throw new IllegalStateException("closed");
    } else {
        this.buffer.writeLong(v);
        return this.emitCompleteSegments();
    }
}

關鍵就在 emitCompleteSegments():

public BufferedSink emitCompleteSegments() throws IOException {
    if (this.closed) {
        throw new IllegalStateException("closed");
    } else {
        long byteCount = this.buffer.completeSegmentByteCount();
        if (byteCount > 0L) {
            this.sink.write(this.buffer, byteCount);
        }
        return this;
    }
}

它先判斷是否已關閉,接著把 buffer 中「已完整」的區塊寫入真正的 sink,最後回傳自身以支援鏈式呼叫。這種「先累積、再批次送出」的策略,正是緩衝 I/O 減少系統呼叫次數的核心手法。

五、Buffer 與 SegmentPool:借鑑 Message 的循環利用

支撐整個緩衝機制的,是一個叫 Buffer 的類。它同時是 BufferedSink 與 BufferedSource 的實作,因此既能讀也能寫。其內部使用 Segment 串成鏈表,並透過 SegmentPool 做物件回收——這個設計與 Android 中 Message 的複用機制幾乎如出一轍。

final class SegmentPool {
    static final long MAX_SIZE = 65536L;
    static Segment next;
    static long byteCount;

    private SegmentPool() { }

    static Segment take() {
        synchronized (SegmentPool.class) {
            if (next != null) {
                Segment result = next;
                next = result.next;
                result.next = null;
                byteCount -= 2048L;
                return result;
            }
        }
        return new Segment();
    }

    static void recycle(Segment segment) {
        if (segment.next == null && segment.prev == null) {
            if (!segment.shared) {
                synchronized (SegmentPool.class) {
                    if (byteCount + 2048L <= MAX_SIZE) {
                        byteCount += 2048L;
                        segment.next = next;
                        segment.pos = segment.limit = 0;
                        next = segment;
                    }
                }
            }
        } else {
            throw new IllegalArgumentException();
        }
    }
}

next 指向池中下一個可用元素。take() 先檢查池中有沒有現成的,有就取用、沒有才 new;recycle() 則把不再使用的 Segment 丟回池中,且用 MAX_SIZE 設了上限,避免池本身無限膨脹。 frequent I/O 場景下,這大幅減少了 GC 壓力。

六、Okio 類:對外的統一入口

對外暴露的門面就是 Okio 這個類,內部全是靜態方法。最常用的一組是「把 Source/Sink 包裝成帶緩衝的版本」:

Okio.buffer(sink)
Okio.buffer(source)

而 Source 與 Sink 本身怎麼來?同樣在 Okio 類裡。資料的來源或目的可以是檔案、串流或 Socket:

Okio.sink(new File("***"));
Okio.sink(new FileOutputStream(new File("***")));
Okio.sink(new Socket("***", 8888));

Okio.source(new File("***"));
Okio.source(new FileInputStream(new File("***")));
Okio.source(new Socket("****", 8888));

七、實戰:檔案讀寫

public static void main(String[] args) {
    Source source = null;
    BufferedSource bufferedSource = null;
    try {
        File file = new File("resources/test.txt");
        source = Okio.source(file);
        bufferedSource = Okio.buffer(source);
        String content = bufferedSource.readUtf8();
        System.out.println(content);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(bufferedSource);
    }

    Sink sink = null;
    BufferedSink bufferedSink = null;
    try {
        File dest = new File("resources/dest.txt");
        sink = Okio.sink(dest);
        bufferedSink = Okio.buffer(sink);
        bufferedSink.writeUtf8("11111111111");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(bufferedSink);
    }
}

public static void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (RuntimeException rethrown) {
            throw rethrown;
        } catch (Exception ignored) { }
    }
}

八、實戰:gzip 壓縮與解壓縮

public static void main(String[] args) {
    // 壓縮寫入
    Sink sink = null;
    BufferedSink bufferedSink = null;
    try {
        File dest = new File("resources/gzip.txt");
        sink = Okio.sink(dest);
        GzipSink gzipSink = new GzipSink(sink);
        bufferedSink = Okio.buffer(gzipSink);
        bufferedSink.writeUtf8("android vs ios");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(bufferedSink);
    }

    // 解壓讀取
    Source source = null;
    BufferedSource bufferedSource = null;
    try {
        File file = new File("resources/gzip.txt");
        source = Okio.source(file);
        GzipSource gzipSource = new GzipSource(source);
        bufferedSource = Okio.buffer(gzipSource);
        String content = bufferedSource.readUtf8();
        System.out.println(content);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(bufferedSource);
    }
}

驗證方式很直接:寫出的檔案不是亂碼,讀回來的字串與原本一致,就代表正確。

九、對比傳統寫法

同樣的 gzip 壓縮與解壓縮,用原生 API 會長這樣:

public class GzipUtil {

    /** GZIP 壓縮 */
    public static byte[] gzip(byte[] data) throws Exception {
        if (data == null || data.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));
        byte[] buf = new byte[512];
        int len;
        try {
            GZIPOutputStream zos = new GZIPOutputStream(out);
            while ((len = bis.read(buf)) != -1) {
                zos.write(buf, 0, len);
                zos.flush();
            }
            bis.close();
            zos.close();
            return out.toByteArray();
        } finally {
            if (out != null) {
                try { out.close(); } catch (Exception e2) { }
            }
        }
    }

    /** Gzip 解壓縮 */
    public static byte[] unGzip(byte[] b) {
        if (b == null || b.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        try {
            GZIPInputStream gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            Log.e(TAG, "uncompress error", e);
        } finally {
            try {
                if (out != null) { out.close(); }
                if (in != null) { in.close(); }
            } catch (Exception e2) { }
        }
        return null;
    }
}

對比之下,Okio 版本少了幾個數量級的樣板:不用自己開 BufferedInputStream、不用手動管理 byte 陣列與讀寫迴圈、不用在 finally 裡一層層關流。更重要的是,壓縮這件事從「額外的串流層」變成了「一個可替換的裝飾器」——把 GzipSink 換掉,其他程式碼完全不用動。

十、還有一個 ByteString

Okio 另外提供了 ByteString 類,可以對位元組序列做各種轉換:轉成 UTF-8 字串、Base64、hex,或計算 MD5、SHA-256 雜湊值。原本需要引入額外函式庫或自己拼 MessageDigest 的事,現在幾行就能完成。

結語

Okio 的價值不只是「寫得短」,而是它把 I/O 這件事的抽象層次整理得相當乾淨:讀寫對稱、緩衝可組合、壓縮可替換、資源回收有節制。在合適的地方適度使用,一定能為你的開發帶來不少便利。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved