参考
https://github.com/square/okio
深入理解okio的优化思想
https://blog.csdn.net/zoudifei/article/details/51232711#t4
Okio从懵逼到掌握
https://www.jianshu.com/p/84f1f4152124
理解
okio核心的优化在于将原来传统的拷贝文件时需要,使用到
输入缓存,中间自定义缓存, 输出缓存,并进行内存拷贝的工作:
File original = new File("hello.txt");
InputStream in = new BufferedInputStream(new FileInputStream(original));
OutputStream out = new BufferedOutStream(new FileOutputStream(copied));
byte[] buffer = new byte[1024];
int lengthRead;
while((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
优化为:
将输入Buffer的Segment双向链表.直接利用链表指针的方式合并到输出Buffer的Segment双向列表.减少内存的拷贝.
Buffer实现了BufferSink和BufferSource是okio的核心类可读可写;管理内存真正的存储单元Segment.
文件拷贝代码如下:
BufferedSource bufferedSource = Okio.buffer(Okio.source(src));
BufferedSink bufferedSink = Okio.buffer(Okio.sink(dest));
bufferedSink.writeAll(bufferedSource);
bufferedSink.close();