Android Okio使用

Okio使用

概述

Okio不是用来完全替代Java IO,Okio本身是基于Java IO,存储和处理数据变得更加容易,Okio的执行效率比Java IO快了很多。

Okio同时也是OkHttp的底层IO库。

依赖库

implementation 'com.squareup.okio:okio:2.4.3'

基本使用

写操作

try (BufferedSink sink = Okio.buffer(Okio.sink(new File("text.txt")))) {
    sink.writeInt(65);
    sink.writeUtf8("hello okio");
    sink.writeUtf8("安卓");
} catch (IOException e) {
    e.printStackTrace();
}

读操作

try (BufferedSource source = Okio.buffer(Okio.source(new File("text.txt")))) {
    String s = source.readUtf8();
    System.out.println(s);
} catch (IOException e) {
    e.printStackTrace();
}

文件复制

try (BufferedSource source = Okio.buffer(Okio.source(new File("text.txt")));
     BufferedSink sink = Okio.buffer(Okio.sink(new File("new_text.txt")))) {
    byte[] bytes = new byte[1024];
    int len;
    while ((len = source.read(bytes)) != -1) {
        sink.write(bytes, 0, len);
    }
} catch (IOException e) {
    e.printStackTrace();
}

等价于

try (BufferedSource bufferedSource = Okio.buffer(Okio.source(new File("text.txt")));
     BufferedSink bufferedSink = Okio.buffer(Okio.sink(new File("new_text.txt")))) {
    bufferedSink.writeAll(bufferedSource);
} catch (IOException e) {
    e.printStackTrace();
}

Gzip

写入数据

try (Sink sink = Okio.sink(new File("text.txt"));
     GzipSink gzipSink = new GzipSink(sink);
     BufferedSink bufferedSink = Okio.buffer(gzipSink)) {

    bufferedSink.writeUtf8("hello");
    bufferedSink.writeUtf8("安卓");

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

读取数据

try {
    Source source = Okio.source(new File("text.txt"));
    GzipSource gzipSource = new GzipSource(source);
    BufferedSource bufferedSource = Okio.buffer(gzipSource);
    String s = bufferedSource.readUtf8();
    System.out.println(s);

} catch (IOException e) {
    e.printStackTrace();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值