A detailed explanation of Okio input and output streams

In the source code of OkHttp, we can often see Okiothe figure of . In this article, we will take it Okioout for a detailed introduction and study.

  • Brief introduction to the concept of input and output
  • Introduction to Okio
  • Introducing Okio into the project
  • API introduction and usage introduction

1. Input and output

Before formally introducing Okio, let us first recall 输入/输出流the concept of Okio.

  • 输入流:外设——>内存
    Read data from various peripherals (such as keyboards, files, networks, databases, etc.) into memory;
    Input stream: Peripherals --> Memory
  • 输出流:内存——>外设
    Contrary to the input stream, it writes memory data to various peripherals (such as files, networks, databases, displays, etc.);
    Output stream: Memory --> Peripherals

2. Introduction to Okio

Okio最初是作为OkHttp的一个组件Appears, it is the underlying IO library used by OkHttp to implement HTTP protocol data construction and analysis. Compared with the traditional java.io and java.nio, it performs data read and write operations such as 文件, and so on .网络更加便捷、高效

Okio main structure

OkioThe design idea of ​​is to encapsulate the data 读写operation into a unified interface, namely Sourceand Sink, where the input is Source and the output is Sink .

  • OkioBufferand are also provided ByteStringto 封装和操作字节数据improve the efficiency of data reading and writing.
  • At the same time, Okiosome tool methods are also provided, such as creating from InputStreamor , etc.OutputStreamBufferedSourceBufferedSink

3. Introducing Okio

The official Okio API address is:
https://square.github.io/okio/

Okio Github open source address is:
https://github.com/square/okio

When using Okio, we can check the official latest version and introduce Okio in the following way:

implementation("com.squareup.okio:okio:3.2.0")

4. Introduction and use of API

  • Buffer introduction and API usage introduction
  • Introduction to ByteString and Introduction to API Usage
  • Source and Sink usage introduction

4.1 Buffer

BufferYes , it is the interface implementation class of and 一个大小可变的字节缓冲区in Okio , and the user realizes the buffering and reading and writing of byte data.BufferBufferedSourceBufferedSink

The official API description is as follows:
Official API description

  • BufferCan be done Arraylistlike that, no need to pre-set the size of the buffer, but along with it 数据的增加自动扩充缓冲区大小.
  • BufferConsists of many Segmentfragments, Segmentmaintaining one in each 字节数组.
  • BufferIt is managed in the form of a linked list Segment. When using Bufferthe buffer byte data movement, it only changes Segmentthe ownership of the byte array, thereby improving the movement efficiency of the byte array.

okio.BufferAn example of how the byte buffer is used is as follows:

import okio.Buffer;

Buffer buffer = new Buffer();
// 向缓冲区写入数据
buffer.writeUtf8("key");
buffer.writeByte('=');
buffer.writeUtf8("value");

// 缓冲区字节大小
int byteCount = buffer.size();

// 读取换区中的全部字节数据
byte[] byteArray = buffer.readByteArray();
// 以Utf8编码的形式输出所有字符串
String result = buffer.readUtf8();

// 清空缓冲区
buffer.clear();

4.2 ByteString

ByteStringIt is maintained in , which can encode and decode strings such as , , , etc. 大小不可变的字节数组on the data stored in the byte array . It is more like a tool class, in which it is an important application scenario .base64utf8md5sha256
ByteStringOkio也是在网络传输中对数据进行编码和解码工作

The official API description is as follows:
Official API description

Some of its static methods and public methods are shown in the following figure:

Static methods of ByteString

Public methods of ByteString

okio.ByteStringExamples of how to use are as follows:

import okio.ByteString;

// utf8编码
ByteString byteString = ByteString.encodeUtf8("hello");
// HEX
ByteString byteString = ByteString.decodeHex("hello");
// 输出utf8字符串
String result = byteString.utf8();

4.3 Source and Sink

Source and Sink mentioned earlier that the input is Source and the output is Sink . In Okio, Sourceand Sinkfor data , it provides a set of standard IO read and write methods, which can facilitate data read and write operations 读取.写入抽象类

// Okio源码:输入流 Source
// Source 接口类,最主要的方法是 read
public interface Source extends Closeable {
	// 读字节数据
    long read(Buffer var1, long var2) throws IOException;
    // timeout
    Timeout timeout();
    void close() throws IOException;
}
// Okio源码:输出流 Sink 
// Sink 接口类,最主要的方法是 write
public interface Sink extends Closeable, Flushable {
	// 写字节数据
    void write(Buffer var1, long var2) throws IOException;
    void flush() throws IOException;
    Timeout timeout();
    void close() throws IOException;
}

Take out the Okio structure diagram shown above:

  • SourceThe final implementation class of is RealBufferedSource;
  • SinkThe final implementation class of is RealBufferedSink;

Okio main structure

Use to okio.Sourceread data from a file, the code example is as follows:

// 使用 Source 从文件中读取数据
public static void readLines(File file) throws IOException {
    
    
    // 输入流
    Source fileSource = Okio.source(file);
    // 构建 BufferedSource
    RealBufferedSource bufferedSource = Okio.buffer(fileSource);
    // 循环读取
    while (true) {
    
    
        // 读取行数据
        String line = bufferedSource.readUtf8Line();
        if (line == null) {
    
    
            break;
        }
    }
}

Use to okio.Sinkwrite data to the file, the code example is as follows:

// 使用 Sink 向文件中写入数据
public static void writeToFile(File file) throws IOException {
    
    
	// 创建输出流
    Sink fileSink = Okio.sink(file);
    // 构造 BufferedSink
    RealBufferedSink bufferedSink = Okio.buffer(fileSink);
    // 向文件中写入数据
    bufferedSink.writeUtf8("Hello");
    bufferedSink.writeUtf8("\n");
    bufferedSink.writeAll(Okio.source(new File("my.txt")));
}

5. Reference

Okio API:
https://square.github.io/okio/

Okio Github:
https://github.com/square/okio

Java stream:
http://c.biancheng.net/view/1119.html

= THE END =

The article was first published on the official account "CODING Technology Pavilion". If the article is helpful to you, please pay attention to my official account.

Guess you like

Origin blog.csdn.net/aiwusheng/article/details/131716994