andorid jar/库源码解析之okio

目录:andorid jar/库源码解析 html

Okio:

  做用:

    说白了,就是一个IO库,基于java原生io。来进行操做,内部作了优化,简洁,高效。因此受到了一部分人的喜欢和使用java

  栗子:

  读写文件。git

    private void ReadFile() {
        try {
            InputStream in = new FileInputStream(new File("/sdcard/a.txt")); // 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){
            System.out.print("error " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void WriteFile(){
        BufferedSink bSink = null;
        try {
            boolean isCreate = false;
            File file = new File("/sdcard/a.txt");
            if (!file.exists()) {
                isCreate = file.createNewFile();
            } else {
                isCreate = true;
            }

            //写入操做
            if (isCreate) {
                Sink 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();
            }

            System.out.print("success");
        }catch (Exception e){
            e.printStackTrace();
            System.out.print("error " + e.getMessage());
        }finally {
            try {
                if (null != bSink) {
                    bSink.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

  源码解读:

File file = new File("/sdcard/a.txt");
Sink sink = Okio.sink(file);

  一、定义文件,github

  二、传入文件,sink内部,建立一个文件写入流  new FileOutputStream(file)的优化

  三、传递流对象给Okio的sink方法。返回一个Sink 的接口的匿名对象,对象中提供的方法,能够访问到传入的流,对流进行操做。(write,flush,close)this

BufferedSink bSink = Okio.buffer(sink);
bSink.writeUtf8("testtest");

  一、构造一个 RealBufferedSink 对象,并传入接口Sink的接口对象。spa

  二、调用 RealBufferedSink 对象的,write方法,写数据。code

  三、在RealBufferedSink对象内部,维护有一个 okio.Buffer 对象,写入方法,首先写入Buffer内部。而后调用 sink的write方法进行写入到流中。htm

  四、这里的okio.Buffer,用于高效复制的时候使用。对象

 
 
InputStream in = new FileInputStream(new File("/sdcard/a.txt")); 
//2.缓冲源
Source source = Okio.source(in);
//3.buffer
Buffer sink = new Buffer();
source.read(sink, in.read());
//4.将数据读入buffer
System.out.print(sink.readUtf8());

  一、传入文件流,返回一个 Source接口对象,接口方法中使用了 传入的流进行操做。(read,close)

  二、构造一个Buffer对象。用于对Source接口对象,进行操做,Buffer中包含更多方法。

  三、调用 source的read方法,先建立一个数据段(Segment),而后从流中读取数据,写入到数据段中。

  四、readUtf8,从数据段中读取数据,这里涉及到了一个判断,(根据当前数据读取位置和须要读取的数据的长度,进行断定,若是当前数据段已经读完,就须要释放下一个数据段,供下次读取。

  源码:https://github.com/square/okio

  引入:

implementation 'com.squareup.okio:okio:1.9.0'
相关文章
相关标签/搜索