編輯:關於 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 展開了一組職責清晰的實作:
RealBufferedSink 與 RealBufferedSource。
BufferedSink 定義了一系列寫入緩衝區的方法:write() 寫 byte 陣列、writeUtf8() 寫字串,還有一整組 writeByte、writeShort、writeInt、writeLong、writeDecimalLong 等。
BufferedSource 的方法與它幾乎一一對應,只是方向相反:readUtf8()、readByte()、readShort()、readInt()、readLong()……
這種高度對稱的 API 設計是 Okio 易用的關鍵:讀與寫的心智模型完全一致,學會一邊就等於學會另一邊。
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 的類。它同時是 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 這個類,內部全是靜態方法。最常用的一組是「把 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) { }
}
}
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 換掉,其他程式碼完全不用動。
Okio 另外提供了 ByteString 類,可以對位元組序列做各種轉換:轉成 UTF-8 字串、Base64、hex,或計算 MD5、SHA-256 雜湊值。原本需要引入額外函式庫或自己拼 MessageDigest 的事,現在幾行就能完成。
Okio 的價值不只是「寫得短」,而是它把 I/O 這件事的抽象層次整理得相當乾淨:讀寫對稱、緩衝可組合、壓縮可替換、資源回收有節制。在合適的地方適度使用,一定能為你的開發帶來不少便利。
別再被騙了:getExternalStorageDirectory並非你想像中的SD卡
別再被騙了:getExternalStorageDirectory並非你想像中的SD卡 前情提要:我的測試機是華為榮耀6,裝過一張16G的內存卡。 由於面試需要,我的演示
Android 自定義 PopupWindow 技巧:定位、動畫與尺寸一次搞定
前言:兩個最頭疼的老大難 自定義 PopupWindow 本身並不難,真正讓人頭疼的其實是兩件事:顯示的定位問題和顯示/消失的動畫問題。 定位之所以麻煩,是因為它常常又牽
Notification 通知欄訊息實作(含自訂版面)
一個很典型的場景:使用者開啟 Activity 後按下 Home 鍵,此時流程會走 onPause() → onStop(),介面不可見。我們就在這個時機送一則 No
自訂通知欄風格:讓訊息顯示在頁面頂端並可點擊回App
通知機制最常見的用法,就是把訊息推到系統的通知欄。本文示範如何自訂通知的版面配置,並讓使用者點擊後回到本程式。 程式碼 package com.lixu.tongzhi