Sink相当于输出流(OutputStream),把内存中的内容输出到硬盘。
关于Flushable、Closeable 、AutoCloseable接口的说明,请参考以下文档:
例子:
try { File file = new File("test.txt"); //如果文件不存在,则自动创建 BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeUtf8("Hello, World"); sink.writeString("测试信息", Charset.forName("UTF-8")); sink.close(); } catch (IOException e) { e.printStackTrace();}
BufferedSink API
/** * 返回Sink内部的Buffer. */ Buffer buffer(); /** * 写ByteString中的数据到Sink */ BufferedSink write(ByteString byteString) throws IOException; /** * 写字节数组到Sink。类似OutputStream#write(byte[]) */ BufferedSink write(byte[] source) throws IOException; /** * 将指定 byte 数组中从偏移量off开始的len个字节写入Sink。类似 * OutputStream#write(byte[], int, int) */ BufferedSink write(byte[] source, int offset, int byteCount) throws IOException; /** * 从Source中移除所有的字节,把他们写入到Sink中,返回读取的字节数。如果Source中 * 的内容已被读取,则返回0。 */ long writeAll(Source source) throws IOException; /** * 从Source中移除byteCount字节,并把他们写入到Sink中 */ BufferedSink write(Source source, long byteCount) throws IOException; /** * 以UTF-8编码把内容写入到Sink中 */ BufferedSink writeUtf8(String string) throws IOException; /** * 以charset编码把内容写入到Sink中 */ BufferedSink writeString(String string, Charset charset) throws IOException; /** * Writes a byte to this sink. */ BufferedSink writeByte(int b) throws IOException; /** * Writes a big-endian short to this sink using two bytes. */ BufferedSink writeShort(int s) throws IOException; /** * Writes a little-endian short to this sink using two bytes. */ BufferedSink writeShortLe(int s) throws IOException; /** * Writes a big-endian int to this sink using four bytes. */ BufferedSink writeInt(int i) throws IOException; /** * Writes a little-endian int to this sink using four bytes. */ BufferedSink writeIntLe(int i) throws IOException; /** * Writes a big-endian long to this sink using eight bytes. */ BufferedSink writeLong(long v) throws IOException; /** * Writes a little-endian long to this sink using eight bytes. */ BufferedSink writeLongLe(long v) throws IOException; /** * Writes a long to this sink in signed decimal form (i.e., as a string in base 10). */ BufferedSink writeDecimalLong(long v) throws IOException; /** * Writes a long to this sink in hexadecimal form (i.e., as a string in base 16). */ BufferedSink writeHexadecimalUnsignedLong(long v) throws IOException; /** * Writes complete segments to the underlying sink, if one exists. Like {@link #flush}, but * weaker. Use this to limit the memory held in the buffer to a single segment. */ BufferedSink emitCompleteSegments() throws IOException; /** * Writes all buffered data to the underlying sink, if one exists. Like {@link #flush}, but * weaker. Call this before this buffered sink goes out of scope so that its data can reach its * destination. */ BufferedSink emit() throws IOException; /** * 返回Sink中的输出流. */ OutputStream outputStream();