美文网首页
Okio学习

Okio学习

作者: 依然淳熙 | 来源:发表于2017-10-29 18:07 被阅读0次

在看Okhttp的源码过程中,发现了Okhttp是封装了Socket进行网络访问的。然后对于Socket输入输出流进行读写用的是Okio了。Okio的Github上面给了一段实例代码如下:

private static final ByteString PNG_HEADER = ByteString.decodeHex("89504e470d0a1a0a");

public void decodePng(InputStream in) throws IOException {
  try (BufferedSource pngSource = Okio.buffer(Okio.source(in))) {
    ByteString header = pngSource.readByteString(PNG_HEADER.size());
    if (!header.equals(PNG_HEADER)) {
      throw new IOException("Not a PNG.");
    }

    while (true) {
      Buffer chunk = new Buffer();

      // Each chunk is a length, type, data, and CRC offset.
      int length = pngSource.readInt();
      String type = pngSource.readUtf8(4);
      pngSource.readFully(chunk, length);
      int crc = pngSource.readInt();

      decodeChunk(type, chunk);
      if (type.equals("IEND")) break;
    }
  }
}

private void decodeChunk(String type, Buffer chunk) {
  if (type.equals("IHDR")) {
    int width = chunk.readInt();
    int height = chunk.readInt();
    System.out.printf("%08x: %s %d x %d%n", chunk.size(), type, width, height);
  } else {
    System.out.printf("%08x: %s%n", chunk.size(), type);
  }
}

其实把这段代码读懂了以后基本也就会使用Okio了。至于Okio的源码网上有大神分析~。这是一个读取PNG图像文件的源代码。我刚开始不理解为什么这么读PNG文件。搜索了PNG文件的格式后就懂了。PNG文件格式详解:http://blog.csdn.net/hherima/article/details/45847043
得到信息:对于一个PNG文件来说,其文件头总是由位固定的字节来描述的,HEX: 89 50 4E 47 0D 0A 1A 0A。 看到了吗是不是与ByteString.decodeHex("89504e470d0a1a0a"); 这个里面解析的十六进制代码一样。因为PNG文件就是以这个格式开头的。。同理对应着PNG文件的结构,我们就可以用Okio提供的各种read方法将PNG文件完全读取解析出来。。

相关文章

  • Okio 框架源码学习

    Retrofit,OkHttp,Okio Square 安卓平台网络层三板斧源码学习 基于 okio 1.13.0...

  • Okio学习

    在看Okhttp的源码过程中,发现了Okhttp是封装了Socket进行网络访问的。然后对于Socket输入输出流...

  • Okio学习

    我发现ok系列, 或者说square出品的开源项目, 都喜欢为具体实现类以RealXXX命名. 这可能也是他们...

  • OkHttp 4源码(6)— Okio源码解析

    本文基于Okio 2.4.3源码分析Okio - 官方地址Okio - GitHub代码地址 Okio 介绍 Ok...

  • okio 源码学习笔记

    最近在学习okhttp的过程中,很多地方遇到了okio的功能,okio是square公司封装的IO框架,okhtt...

  • OkIO简单学习

    参考:http://square.github.io/okio/1.x/okio/ 1、引用 compile 'c...

  • Okio 源码分析

    Okio 源码分析 Okio , Java, Java IO OkIo 是 OKHTTP 中使用的 一个 IO的框...

  • Okio源码分析

    https://github.com/square/okio Okio is a library that com...

  • RN 安卓老项目报错

    Could not resolve com.squareup.okio:okio:{strictly 1.13.0...

  • Android项目常用dependencies

    ### 网络类 * compile 'com.squareup.okio:okio:1.9.0' * compil...

网友评论

      本文标题:Okio学习

      本文链接:https://www.haomeiwen.com/subject/uslauxtx.html