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

善用 Okio:讓 Android 的 I/O 操作更簡潔

編輯:關於 Android 程式設計

Okio 是 Square 公司出品的一個庫,它填補了 java.io 與 java.nio 的不足,讓數據的讀取、存儲與處理變得更便捷、更高效。值得一提的是,大名鼎鼎的 OkHttp 底層正是靠它來支撐。在實際開發中引入 Okio,往往能事半功倍。

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

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

兩個核心接口:Sink 與 Source

Okio 里有兩個關鍵接口——Sink 和 Source,二者都繼承自 Closeable。你可以簡單地把 Sink 理解為 OutputStream,把 Source 理解為 InputStream,而且它們都支持讀寫超時設置。結構大致如下:

各自還有一個支持緩衝區的子接口 BufferedSink 與 BufferedSource,對應實現類分別是 RealBufferedSink 和 RealBufferedSource。此外,Sink 與 Source 還各有支持 gzip 壓縮的實現類 GzipSink、GzipSource,具備委托能力的抽象類 ForwardingSink、ForwardingSource,以及主要服務於壓縮場景的 InflaterSource、DeflaterSink。整體結構如下:

緩衝區接口的方法設計

BufferedSink 定義了一系列寫入緩衝區的方法:write 寫 byte 數組、writeUtf8 寫字符串,還有 writeByte、writeString、writeShort、writeInt、writeLong、writeDecimalLong 等等。BufferedSource 的方法與之幾乎一一對應,只不過一個是寫、一個是讀,如 readUtf8、readByte、readString、readShort、readInt 等。有興趣的同學可以直接翻源碼細看。

RealBufferedSink 與 RealBufferedSource 的實現思路一致,都是通過「包裝一個 Sink + Buffer」或「Source + Buffer」來完成的:

以 RealBufferedSink 為例,它的一系列 write 方法其實都是直接操作成員變量 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();
    }
}

可見它先判斷 closed 標記是否已關閉,若關閉則拋異常,否則把內容寫入 buffer,最後調用 emitCompleteSegments。而這個方法做的,正是把 buffer 里的內容寫入 sink 成員變量,然後返回自身:

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 與 SegmentPool

這一切的背後,是一個叫 Buffer 的類在撐著。Buffer 是 BufferedSink 和 BufferedSource 的實現類,因此既能讀也能寫。它內部用 Segment 和 SegmentPool 維護著一個鏈表,其循環利用機制與 Android 里 Message 的複用機制如出一轍:

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

    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 <= 65536L) {
                        byteCount += 2048L;
                        segment.next = next;
                        segment.pos = segment.limit = 0;
                        next = segment;
                    }
                }
            }
        }
    }
}

成員變量 next 指向鏈表下一個元素;take 方法先判斷池中有沒有可用的,有就返回、沒有就 new 一個;recycle 則把不再使用的 Segment 重新丟回池中,從而實現 Segment 的複用。

Okio 類:對外暴露的統一入口

Okio 真正暴露給外部使用的是 Okio 這個類,內部有大量靜態方法,比如通過一個 Source 拿到 BufferedSource、通過一個 Sink 拿到 BufferedSink。調用很簡單:

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

但這兩個方法需要你傳入 Sink 或 Source,那它們又從哪來?答案同樣在 Okio 類里——調用 sink 或 source 方法即可獲得,數據來源或去向可以是 File、輸入輸出流、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 (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 (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 壓縮與解壓,也能優雅搞定

網絡請求中常常需要用到 Gzip,Okio 讓這件事變得格外輕鬆:

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 (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 (IOException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(bufferedSource);
    }
}

驗證是否正確,只需看看寫出的文件是否亂碼、讀回來是否與原字符串一致即可。對比傳統那套繁琐的 GZIPOutputStream/GZIPInputStream 寫法,Okio 的簡潔程度高下立判。

ByteString:靈活的位元組處理利器

此外還有一個 ByteString 類,它能變化出各種形態:把 byte 轉成 String,這個 String 可以是 utf8 值,也可以是 base64、md5、sha256 之後的值,總之能變出你想要的那一種。

總的來說,在合適的場景下適當引入 Okio,一定能為你的開發帶來不少便利,何樂而不為呢?

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