Okio 1.9簡單入門
Okio庫是由square公司開發的,補充了java.io和java.nio的不足,更加方便,快速的訪問、存儲和處理你的數據。而OkHttp的底層也使用該庫作為支持。
該庫極大的簡化I/O操作。
Gradle引用如下(最新版:1.9 )
compile 'com.squareup.okio:okio:1.9.0'
Okio類作為OkIo庫暴露給外部使用的類,提供大量的靜態方法;
其有兩個關鍵的接口,Sink和Source,繼承了Closeable接口;
Sink可以簡單的看做OutputStream;->寫操作! ->通過一個Sink獲得一個BufferedSink。
Source可以簡單的看做InputStream。->讀操作! ->通過一個Source獲得BufferedSource,
如下圖:
Sink 與Source類的結構圖如下:
說明:
Sink 有個子類接口 BufferddSink :定義了一系列寫入緩存區的方法
實現類 RealBufferedSink
Source 有個子類接口 BufferedSource :定義了一系列讀取緩存區的方法
實現類RealBufferedSource
支持gzip壓縮的實現類GzipSink和GzipSource及壓縮類DeflaterSink和InflaterSource;
實現類 RealBufferedSink 、RealBufferedSource結構:
Buffer類
Buffer類操作寫動作,但是數據並沒真正的完成寫,而是保存在鏈表(Segment雙向鏈表)中;
具體使用
對Okio庫的整體框架有了基本了解,那么就該實際操作了。
具體步驟如下:
1.調用Okio類的靜態方法獲取Source(Sink)
2.調用Okio類庫的靜態方法,通過剛才獲取的Source(Sink)獲取BufferedSource(BufferedSink)
3.對緩沖區根據實際需求做相應操作
4.若是Sink,須將調用flush()
5.最后close掉,避免內存泄漏
讀取文件
一.在項目根目錄下新建文件“test.txt”,並寫入一些文字;
二.新建Class:-> Okio_Demo
三.進入讀寫操作;
四.在類中新建 main()方法,進行測試!
說明:所有功能都是在類中寫main()方法中進行測試!!
如下圖:
創建文件並寫數據
/**
* 新建文件並寫入數據
*/
private static void create_writer(){
String filename="create.txt";
boolean isCreate=false;
Sink sink;
BufferedSink bSink=null;
try{
//判斷文件是否存在,不存在,則新建!
File file=new File(filename);
if (!file.exists()) {
isCreate=file.createNewFile();
}else {
isCreate=true;
}
//寫入操作
if (isCreate) {
sink=Okio.sink(file);
bSink=Okio.buffer(sink);
bSink.writeUtf8("1");
bSink.writeUtf8("\n");
bSink.writeUtf8("this is new file!");
bSink.writeUtf8("\n");
bSink.writeString("我是每二條",Charset.forName("utf-8"));
bSink.flush();
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (null!=bSink) {
bSink.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
Buffer 寫操作:
/**
*寫buffer
* 在okio中buffer是一個很重要的對象
*/
public static void sinkFromOutputStream(){
String filename = "create.txt";
File file = new File(filename);
//1.構建buffer對象
Buffer data=new Buffer();
//2.向緩沖中寫入文本
data.writeUtf8("afdsa");
//3.可以連續追加,類似StringBuffer
data.writeUtf8("b");
//4.構建字節數組流對象
ByteArrayOutputStream out = new ByteArrayOutputStream();
//5.構建寫緩沖池
// Sink sink = Okio.sink(out);
//6.向池中寫入buffer
try {
Sink sink=Okio.sink(file);
sink.write(data, 2);
} catch (IOException e) {
e.printStackTrace();
}
}
Buffer 讀操作:
/**
* 讀buffer
*/
public static void sourceFromInputStream(){
//1.構建字節數組流
try {
InputStream
in = new ByteArrayInputStream(("adasfdsaf").getBytes());
//2.緩沖源
Source source=Okio.source(in);
//3.buffer
Buffer sink = new Buffer();
source.read(sink,in.read());
//4.將數據讀入buffer
System.out.print(sink.readUtf8());
} catch (Exception e) {
e.printStackTrace();
}
}
Okio工具類—ByteString類,這個類可以用來做各種變化,它將byte轉會為String,而這個String可以是utf8的值,也可以是base64后的值,也可以是md5的值,也可以是sha256的值,總之就是各種變化,最后取得你想要的值。
如:
ByteString.of("ss".getBytes()).base64();
ByteString.of("ss".getBytes()).md5();
ByteString.of("ss".getBytes()).sha1();
ByteString.of("ss".getBytes()).sha256();
最后借用一個大牛的類圖!
Okio的類圖關系如下:
官網地址:
1.OkioAPI