Okio簡(jiǎn)單分析

Okio的傳送門

https://github.com/square/okio


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

  • 接下來(lái)簡(jiǎn)單模擬一個(gè)io操作
  • 定義一個(gè)讀取數(shù)據(jù)的接口,返回byte[ ]BytesReader
  • 定義一個(gè)它的實(shí)現(xiàn)類,用來(lái)讀取byte[]BytesReaderImpl
  • 定義一個(gè)讀取String的接口,用來(lái)讀取StringReader
  • 對(duì)BytesReaderImpl進(jìn)行裝飾,,讓裝飾類支持讀取StringStringReaderImpl
繼承關(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 = "僅僅就是用來(lái)測(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)在來(lái)看看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)建操作

下面開(kāi)始分析源代碼

  • 首先有一點(diǎn)是明白的,就是Source和Sink這兩個(gè)類定義了頂層接口,一個(gè)用來(lái)讀數(shù)據(jù),一個(gè)用來(lái)寫數(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)用的常用接口,可以看到不管是讀還是寫都支持常見(jiàn)的類型,基本類型,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],所以說(shuō)Buffer在okio的讀寫種起著媒介(比較重要)的作用,Buffer的代碼有點(diǎn)多(1600+行)就提出一些比較重要的來(lái)說(shuō)
  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)單的說(shuō)哈后面在回過(guò)來(lái)說(shuō),這里Buffer其實(shí)既有讀的功能也有寫的功能,但是我們的程序里面其實(shí)是可以像調(diào)用java io的api一樣,因?yàn)槔锩姘b了一個(gè)OutputStream和InputStream ,這里還引入了一個(gè)新的對(duì)象,**Segment**
  • 有了大概的了解,就來(lái)看看繼承圖


    okio部分類的繼承圖

繼續(xù)啊

  • 我們構(gòu)造BufferedSource是使用的是Okio.buffer(Okio.sink(fileOut));
    • 首先來(lái)看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ì)象并返回。代碼就不貼了,說(shuō)哈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)部類來(lái)實(shí)例化的,并且里面使用FileInputStream去讀取數(shù)據(jù),然后吧數(shù)據(jù)保存到傳入的Buffer參數(shù)里面,而這個(gè)Buffer是支持讀寫的。所以BufferedSource讀取Buffer里面的數(shù)據(jù),Buffer獲取從FileInputStream里面的數(shù)據(jù)。從這里就可以看出來(lái),Okio效率高就是這個(gè)Buffer在起作用,前面大概說(shuō)了哈Buffer,它里面還有一個(gè)重要的對(duì)象還沒(méi)有說(shuō)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)在可以來(lái)看看Buffer里面是怎么處理數(shù)據(jù)的了,就挑一個(gè)read方法,其實(shí)就是直接將傳入的byte數(shù)據(jù)copy到了segment里面,這里又出來(lái)了一個(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ù)。

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

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