Okio簡(jiǎn)單分析

Okio的傳送門

https://github.com/square/okio


了解Okio之前先了解一個(gè)裝飾者模式(就是java io的思路)

  • 接下來簡(jiǎn)單模擬一個(gè)io操作
  • 定義一個(gè)讀取數(shù)據(jù)的接口,返回byte[ ]BytesReader
  • 定義一個(gè)它的實(shí)現(xiàn)類,用來讀取byte[],BytesReaderImpl
  • 定義一個(gè)讀取String的接口,用來讀取StringReader
  • 對(duì)BytesReaderImpl進(jìn)行裝飾,,讓裝飾類支持讀取String,StringReaderImpl
繼承關(guān)系圖
  • 看看具體的代碼實(shí)現(xiàn)吧 _( 比較簡(jiǎn)單)
    ByteReader && ByteReaderImpl
 public interface BytesReader {
       byte[] readBytes(); //定義一個(gè)讀取byte[]的數(shù)組
 }

 public class BytesReaderImpl implements BytesReader {
   @Override
   public byte[] readBytes() {
       String str = "僅僅就是用來測(cè)試的字符串^_^...";
       return str.getBytes();
   }
}

StringReader && StringReaderImpl

  public interface StringReader extends BytesReader{
      String readString();
  }

  public class StringReaderImpl implements StringReader{
      private BytesReader bytesReader;
      public StringReaderImpl(BytesReader bytesReader) {
          this.bytesReader = bytesReader;
      }
      @Override
      public String readString() {
          byte[] bytes = bytesReader.readBytes();
          return new String(bytes);
      }
      @Override
      public byte[] readBytes() {
          return bytesReader.readBytes();
      }
  }

現(xiàn)在來看看okio的基本用法

public class Test {
    public static void main(String[] args){

       /* BytesReader bytesReader = new BytesReaderImpl();
        StringReader stringReader = new StringReaderImpl(bytesReader);

        System.out.println("readBytes  : "+bytesReader.readBytes().length);
        System.out.println("readString : "+stringReader.readString());*/

        File file = new File("D://demo.txt");
        File fileOut = new File("D://demo1.txt");
        BufferedSink sink = null;
        BufferedSource source = null;
        try {
            sink = Okio.buffer(Okio.sink(fileOut));
            source = Okio.buffer(Okio.source(file));
            byte[] buffer = new byte[12];
            int temp = 0;
            while((temp = source.read(buffer)) != -1){
                System.out.println("temp : "+temp);
                sink.write(buffer,0,temp);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(sink != null){
                    sink.close();
                }
                if(source != null){
                    source.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
  • okio里面有一個(gè),Source接口定義了讀取數(shù)據(jù)的接口,類似InputStream
  • okio里面還有一個(gè),Sink接口定義了寫數(shù)據(jù)的接口,類似OutputStream
  • Source和Sink有兩個(gè)實(shí)現(xiàn)類,BufferedSourceBufferedSink,這兩個(gè)實(shí)現(xiàn)類定義了很多方法,包括文件的讀寫,字符串的讀寫,流的讀寫 等
  • BufferedSource 和 BufferedSink有兩個(gè)之類,RealBufferedSource和RealBufferedSink**,實(shí)際用的時(shí)候其實(shí)是用的這兩個(gè)實(shí)現(xiàn)類
  • Okio這個(gè)類提供了很多靜態(tài)方法,簡(jiǎn)化上面這些類的創(chuàng)建操作

下面開始分析源代碼

  • 首先有一點(diǎn)是明白的,就是Source和Sink這兩個(gè)類定義了頂層接口,一個(gè)用來讀數(shù)據(jù),一個(gè)用來寫數(shù)據(jù)。
    Source && Sink

    public interface Source extends Closeable {
          long read(Buffer sink, long byteCount) throws IOException;
          Timeout timeout();
          @Override void close() throws IOException;
    }
    
      public interface Sink extends Closeable, Flushable {
          void write(Buffer source, long byteCount) throws IOException;
          @Override void flush() throws IOException;
          /** Returns the timeout for this sink. */
          Timeout timeout();
          @Override void close() throws IOException;
    }
    
  • Source和Sink分別有一個(gè)實(shí)現(xiàn)接口BufferedSource(接口)和BufferedSink(接口),這兩個(gè)接口就定義了更加偏向應(yīng)用的常用接口,可以看到不管是讀還是寫都支持常見的類型,基本類型,String,而且Source接口和Sink接口接受的參數(shù)都是Buffer

      public interface BufferedSink extends Sink {
            Buffer buffer();
            BufferedSink write(ByteString byteString) throws IOException;
            BufferedSink write(byte[] source, int offset, int byteCount) throws IOException;
            BufferedSink writeUtf8(String string) throws IOException;
            BufferedSink writeShort(int s) throws IOException;
            .....
      }
    
      public interface BufferedSource extends Source {
             byte readByte() throws IOException;
             short readShort() throws IOException;
             short readShortLe() throws IOException;
             String readUtf8() throws IOException;
             .....
      }   
    
  • 可以看到不管是Source還是Sink接受的參數(shù)都是Buffer [okio.Buffer],所以說Buffer在okio的讀寫種起著媒介(比較重要)的作用,Buffer的代碼有點(diǎn)多(1600+行)就提出一些比較重要的來說
  public final class Buffer implements BufferedSource, BufferedSink, Cloneable {
      Segment head;
      long size;

      @Override public OutputStream outputStream() {
              return new OutputStream() {
                        @Override public void write(int b) {
                            writeByte((byte) b);
                          }

                        @Override public void write(byte[] data, int offset, int byteCount) {
                                Buffer.this.write(data, offset, byteCount);
                          }
                        @Override public void flush(){}
                        @Override public void close() {}
                        @Override public String toString() {
                              return Buffer.this + ".outputStream()";
                         }
              };
        }  
        ...
        @Override public InputStream inputStream() {
                  return new InputStream() {
                        @Override public int read() {
                              if (size > 0) return readByte() & 0xff;
                              return -1;
                          }

                        @Override public int read(byte[] sink, int offset, int byteCount) {
                              return Buffer.this.read(sink, offset, byteCount);
                        }

                      @Override public int available() {
                              return (int) Math.min(size, Integer.MAX_VALUE);
                      }

                    @Override public void close() {
                      }

                    @Override public String toString() {
                            return Buffer.this + ".inputStream()";
                    }
            };
        }
        ....
  }
- 先簡(jiǎn)單的說哈后面在回過來說,這里Buffer其實(shí)既有讀的功能也有寫的功能,但是我們的程序里面其實(shí)是可以像調(diào)用java io的api一樣,因?yàn)槔锩姘b了一個(gè)OutputStream和InputStream ,這里還引入了一個(gè)新的對(duì)象,**Segment**
  • 有了大概的了解,就來看看繼承圖


    okio部分類的繼承圖

繼續(xù)啊

  • 我們構(gòu)造BufferedSource是使用的是Okio.buffer(Okio.sink(fileOut));
    • 首先來看Okio.sink(fileOut),其實(shí)內(nèi)部就一句,return sink(new FileOutputStream(file));,構(gòu)造了一個(gè)FileOutputStream并調(diào)用了,sink(OutputStream out)方法,最終調(diào)用了sink(OutputStream out, Timeout timeout) 這個(gè)方法,其實(shí)就是構(gòu)造了一個(gè)Sink接口對(duì)象并返回。
        private static Sink sink(final OutputStream out, final Timeout timeout) {
      if (out == null) throw new IllegalArgumentException("out == null");
      if (timeout == null) throw new IllegalArgumentException("timeout == null");
    
      return new Sink() {
        @Override public void write(Buffer source, long byteCount) throws IOException {
          checkOffsetAndCount(source.size, 0, byteCount);
          while (byteCount > 0) {
            timeout.throwIfReached();
            Segment head = source.head;
            int toCopy = (int) Math.min(byteCount, head.limit - head.pos);
            out.write(head.data, head.pos, toCopy);
    
            head.pos += toCopy;
            byteCount -= toCopy;
            source.size -= toCopy;
    
            if (head.pos == head.limit) {
              source.head = head.pop();
              SegmentPool.recycle(head);
            }
          }
        }
    
        @Override public void flush() throws IOException {
          out.flush();
        }
    
        @Override public void close() throws IOException {
          out.close();
        }
    
        @Override public Timeout timeout() {
          return timeout;
        }
    
        @Override public String toString() {
          return "sink(" + out + ")";
        }
      };
    }
    
  • 上面的Sink返回了以后傳遞給了Okio.buffer方法,這個(gè)方法里面實(shí)際就是實(shí)例化了一個(gè)RealBufferedSink對(duì)象并返回。代碼就不貼了,說哈RealBufferedSink大概做了些什么,首先是RealBufferedSink里面包含了一個(gè)Buffer(可讀可寫)對(duì)象,在調(diào)用RealBufferedSink的時(shí)候,實(shí)際上就是調(diào)用的Buffer對(duì)象的write方法。

  • BufferedSource和BufferedSink的處理是類似的這里就不啰嗦了。


小結(jié)前面提到的流程

  • 在構(gòu)造BufferedSource的時(shí)候會(huì)傳遞一個(gè)Source到Okio.buffer方法里面,而這個(gè)Source是一個(gè)匿名內(nèi)部類來實(shí)例化的,并且里面使用FileInputStream去讀取數(shù)據(jù),然后吧數(shù)據(jù)保存到傳入的Buffer參數(shù)里面,而這個(gè)Buffer是支持讀寫的。所以BufferedSource讀取Buffer里面的數(shù)據(jù),Buffer獲取從FileInputStream里面的數(shù)據(jù)。從這里就可以看出來,Okio效率高就是這個(gè)Buffer在起作用,前面大概說了哈Buffer,它里面還有一個(gè)重要的對(duì)象還沒有說Segment

繼續(xù)哈

  • Segment對(duì)象,Segment的源碼不是很多,實(shí)現(xiàn)的實(shí)現(xiàn)其實(shí)就是一個(gè)雙向鏈表。里面定義了一個(gè)byte[]和前一個(gè)節(jié)點(diǎn)的引用以及后一個(gè)節(jié)點(diǎn)的引用
final class Segment {
  /** The size of all segments in bytes. */
  static final int SIZE = 8192;
  /** Segments will be shared when doing so avoids {@code arraycopy()} of this many bytes. */
  static final int SHARE_MINIMUM = 1024;
  final byte[] data;
  int pos;
  int limit;
  boolean shared;
  boolean owner;
  Segment next;
  Segment prev;

  Segment() {
    this.data = new byte[SIZE];
    this.owner = true;
    this.shared = false;
  }
  ...
  public Segment pop() {
    Segment result = next != this ? next : null;
    prev.next = next;
    next.prev = prev;
    next = null;
    prev = null;
    return result;
  }

  public Segment push(Segment segment) {
    segment.prev = this;
    segment.next = next;
    next.prev = segment;
    next = segment;
    return segment;
  }
 ...
  public void writeTo(Segment sink, int byteCount) {
    if (!sink.owner) throw new IllegalArgumentException();
    if (sink.limit + byteCount > SIZE) {
      // We can't fit byteCount bytes at the sink's current position. Shift sink first.
      if (sink.shared) throw new IllegalArgumentException();
      if (sink.limit + byteCount - sink.pos > SIZE) throw new IllegalArgumentException();
      System.arraycopy(sink.data, sink.pos, sink.data, 0, sink.limit - sink.pos);
      sink.limit -= sink.pos;
      sink.pos = 0;
    }
    System.arraycopy(data, pos, sink.data, sink.limit, byteCount);
    sink.limit += byteCount;
    pos += byteCount;
  }
}
  • 現(xiàn)在可以來看看Buffer里面是怎么處理數(shù)據(jù)的了,就挑一個(gè)read方法,其實(shí)就是直接將傳入的byte數(shù)據(jù)copy到了segment里面,這里又出來了一個(gè)新的類SegmentPool
@Override public int read(byte[] sink, int offset, int byteCount) {
   checkOffsetAndCount(sink.length, offset, byteCount);

   Segment s = head;
   if (s == null) return -1;
   int toCopy = Math.min(byteCount, s.limit - s.pos);
   System.arraycopy(s.data, s.pos, sink, offset, toCopy);

   s.pos += toCopy;
   size -= toCopy;

   if (s.pos == s.limit) {
     head = s.pop();
     SegmentPool.recycle(s);
   }

   return toCopy;
 }
  • SegmentPool就是一個(gè)回收池~~,讀取和寫入不斷的回收利用,同一個(gè)byte[]多次利用。

最后貼一個(gè)okio的整個(gè)繼承圖吧

點(diǎn)擊查看大圖

Nothing is certain in this life. The only thing i know for sure is that. I love you and my life. That is the only thing i know. have a good day

:)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,182評(píng)論 6 543
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,489評(píng)論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 178,290評(píng)論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,776評(píng)論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,510評(píng)論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,866評(píng)論 1 328
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,860評(píng)論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,036評(píng)論 0 290
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,585評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,331評(píng)論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,536評(píng)論 1 374
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,058評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,754評(píng)論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,154評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,469評(píng)論 1 295
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,273評(píng)論 3 399
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,505評(píng)論 2 379

推薦閱讀更多精彩內(nèi)容

  • 前言 Okio是一款輕量級(jí)IO框架,由安卓大區(qū)最強(qiáng)王者Square公司打造,是著名網(wǎng)絡(luò)框架OkHttp的基石。Ok...
    開發(fā)者小王閱讀 14,288評(píng)論 5 50
  • 1.OkHttp源碼解析(一):OKHttp初階2 OkHttp源碼解析(二):OkHttp連接的"前戲"——HT...
    隔壁老李頭閱讀 10,919評(píng)論 24 43
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,826評(píng)論 18 139
  • square在開源社區(qū)的貢獻(xiàn)是卓越的,這里是square在Android領(lǐng)域貢獻(xiàn)的開源項(xiàng)目。 1. okio概念 ...
    王英豪閱讀 1,207評(píng)論 0 2
  • 現(xiàn)在經(jīng)?;貞浶r(shí)候,仿佛昨天剛下課,今天突然就穿越過來。中間那段時(shí)間刷刷刷地飛過去,曾經(jīng)以為很久遠(yuǎn)的事情突然就變得...
    木目木目閱讀 303評(píng)論 0 0