首先贴一下牛逼的Square公司开源的框架地址Square开源框架,okio帮助文档地址:okio的api地址。
看文档的截图发现类不是很多,瞬间感觉很轻松有木有,看源码的规则就是首先你得会用,会用了,那么就会知道入口函数在哪,然后一步一步的剖析代码
public interface Sink extends Closeable, Flushable {
/** Removes {@code byteCount} bytes from {@code source} and appends them to this. */
void write(Buffer source, long byteCount) throws IOException;
/** Pushes all buffered bytes to their final destination. */
@Override void flush() throws IOException;
/** Returns the timeout for this sink. */
Timeout timeout();
/**
* Pushes all buffered bytes to their final destination and releases the
* resources held by this sink. It is an error to write a closed sink. It is
* safe to close a sink more than once.
*/
@Override void close() throws IOException;
}
public interface Source extends Closeable {
/**
* Removes at least 1, and up to {@code byteCount} bytes from this and appends
* them to {@code sink}. Returns the number of bytes read, or -1 if this
* source is exhausted.
*/
long read(Buffer sink, long byteCount) throws IOException;
/** Returns the timeout for this source. */
Timeout timeout();
/**
* Closes this source and releases the resources held by this source. It is an
* error to read a closed source. It is safe to close a source more than once.
*/
@Override void close() throws IOException;
}
读接口只实现了读写流的Closeable方法,而写接口还实现了Flushable方法,找到jdk源码咱们看一下这两个接口都实现了啥
public interface Closeable {
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
}
Closeable就需要实现close()方法就好了,那么Flushable呢?
public interface Flushable {
/**
* Flushes this stream by writing any buffered output to the underlying
* stream.
*
* @throws IOException If an I/O error occurs
*/
void flush() throws IOException;
}
Okio.sink(new OutputStream())填入字节流为你返回sink写接口
Okio.sink(socket);填入套接字为你返回sink写接口(搜嘎写sokect通信时可以用此类)
Okio.sink(path, options);填入路径返回sink写接口(搜嘎写sokect通信时可以用此类)
看例子:
最基本的写用法:
String filePath = "D:/1.txt";
try {
Sink sink = Okio.sink(new File(filePath));
BufferedSink buffer = Okio.buffer(sink);
buffer.writeString("www", Charset.forName("UTF-8"));
buffer.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最基本的读用法:
String filePath = "D:/1.txt";
try {
Source source = Okio.source(new File(filePath));
BufferedSource buffer = Okio.buffer(source);
String h = buffer.readString(Charset.forName("UTF-8"));
System.out.println(h);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
先从写开始入手,进入
Okio.sink()方法
public static Sink sink(File file) throws FileNotFoundException {
if (file == null) throw new IllegalArgumentException("file == null");
return sink(new FileOutputStream(file));
}
额......,这不是包装了
FileOutputStream方法吗,我晕,继续:
public static Sink sink(OutputStream out) {
return sink(out, new Timeout());
}
加了一个
Timeout类,什么鬼,猜测一下和超时有关的,写东西用超时作甚?带着懵逼疑问继续
private static Sink sink(final OutputStream out, final Timeout timeout) {
if (out == null) throw new IllegalArgumentException("out == null");
if (timeout == null) throw new IllegalArgumentException("timeout == null");
return new Sink() {
@Override public void write(Buffer source, long byteCount) throws IOException {
checkOffsetAndCount(source.size, 0, byteCount);
while (byteCount > 0) {
timeout.throwIfReached();
Segment head = source.head;
int toCopy = (int) Math.min(byteCount, head.limit - head.pos);
out.write(head.data, head.pos, toCopy);
head.pos += toCopy;
byteCount -= toCopy;
source.size -= toCopy;
if (head.pos == head.limit) {
source.head = head.pop();
SegmentPool.recycle(head);
}
}
}
@Override public void flush() throws IOException {
out.flush();
}
@Override public void close() throws IOException {
out.close();
}
@Override public Timeout timeout() {
return timeout;
}
@Override public String toString() {
return "sink(" + out + ")";
}
};
}
public static BufferedSink buffer(Sink sink) {
return new RealBufferedSink(sink);
}
装饰者模式,把
sink用
RealBufferedSink包装起来,那么最后执行写方法的就是它了
@Override public BufferedSink writeString(String string, Charset charset) throws IOException {
if (closed) throw new IllegalStateException("closed");
buffer.writeString(string, charset);
return emitCompleteSegments();
}
然后调用Buffer类的写方法
public Buffer writeString(String string, Charset charset) {
return writeString(string, 0, string.length(), charset);
}
最后进入Buffered里开始写
public Buffer writeUtf8(String string, int beginIndex, int endIndex) {
if (string == null) throw new IllegalArgumentException("string == null");
if (beginIndex < 0) throw new IllegalArgumentException("beginIndex < 0: " + beginIndex);
if (endIndex < beginIndex) {
throw new IllegalArgumentException("endIndex < beginIndex: " + endIndex + " < " + beginIndex);
}
if (endIndex > string.length()) {
throw new IllegalArgumentException(
"endIndex > string.length: " + endIndex + " > " + string.length());
}
// Transcode a UTF-16 Java String to UTF-8 bytes.
for (int i = beginIndex; i < endIndex;) {
//获得单个字符的编码
int c = string.charAt(i);
//此数值在ASCII编码范围内的处理,这时c不需要处理
if (c < 0x80) {
Segment tail = writableSegment(1);
//获取存储的数据的data
byte[] data = tail.data;
int segmentOffset = tail.limit - i;
//运行限制取最大容量和当前要输入的字节量的最小值
int runLimit = Math.min(endIndex, Segment.SIZE - segmentOffset);
// Emit a 7-bit character with 1 byte.
data[segmentOffset + i++] = (byte) c; // 0xxxxxxx
// Fast-path contiguous runs of ASCII characters. This is ugly, but yields a ~4x performance
// improvement over independent calls to writeByte().
while (i < runLimit) {
c = string.charAt(i);
if (c >= 0x80) break;
data[segmentOffset + i++] = (byte) c; // 0xxxxxxx
}
int runSize = i + segmentOffset - tail.limit; // Equivalent to i - (previous i).
//像nio流一样将limit极限设置为输入了多少字节
tail.limit += runSize;
//buffer类已经储存的size
size += runSize;
}
//假如c的值需要两个字节表示
else if (c < 0x800) {
// Emit a 11-bit character with 2 bytes.
//将字节的二进制转化为utf-8的表示方式,当最多十一个字节的时候
writeByte(c >> 6 | 0xc0); // 110xxxxx
writeByte(c & 0x3f | 0x80); // 10xxxxxx
i++;
}
//需要三个字节的时候表示方法
else if (c < 0xd800 || c > 0xdfff) {
// Emit a 16-bit character with 3 bytes.
//将字节的二进制转化为utf-8的表示方式,当最多16-bit的时候
writeByte(c >> 12 | 0xe0); // 1110xxxx
writeByte(c >> 6 & 0x3f | 0x80); // 10xxxxxx
writeByte(c & 0x3f | 0x80); // 10xxxxxx
i++;
}
//utf-8变成编码最多四个字节表示
else {
// c is a surrogate. Make sure it is a high surrogate & that its successor is a low
// surrogate. If not, the UTF-16 is invalid, in which case we emit a replacement character.
int low = i + 1 < endIndex ? string.charAt(i + 1) : 0;
if (c > 0xdbff || low < 0xdc00 || low > 0xdfff) {
writeByte('?');
i++;
continue;
}
// UTF-16 high surrogate: 110110xxxxxxxxxx (10 bits)
// UTF-16 low surrogate: 110111yyyyyyyyyy (10 bits)
// Unicode code point: 00010000000000000000 + xxxxxxxxxxyyyyyyyyyy (21 bits)
int codePoint = 0x010000 + ((c & ~0xd800) << 10 | low & ~0xdc00);
// Emit a 21-bit character with 4 bytes.
writeByte(codePoint >> 18 | 0xf0); // 11110xxx
writeByte(codePoint >> 12 & 0x3f | 0x80); // 10xxxxxx
writeByte(codePoint >> 6 & 0x3f | 0x80); // 10xxyyyy
writeByte(codePoint & 0x3f | 0x80); // 10yyyyyy
i += 2;
}
}
return this;
}
1. ASCII码
我们知道,在计算机内部,所有的信息最终都表示为一个二进制的字符串。每一个二进制位(bit)有0和1两种状态,因此八个二进制位就可以组合出256种状态,这被称为一个字节(byte)。也就是说,一个字节一共可以用来表示256种不同的状态,每一个状态对应一个符号,就是256个符号,从0000000到11111111。
上个世纪60年代,美国制定了一套字符编码,对英语字符与二进制位之间的关系,做了统一规定。这被称为ASCII码,一直沿用至今。
ASCII码一共规定了128个字符的编码,比如空格“SPACE”是32(二进制00100000),大写的字母A是65(二进制01000001)。这128个符号(包括32个不能打印出来的控制符号),只占用了一个字节的后面7位,最前面的1位统一规定为0。
2、非ASCII编码
英语用128个符号编码就够了,但是用来表示其他语言,128个符号是不够的。比如,在法语中,字母上方有注音符号,它就无法用ASCII码表示。于是,一些欧洲国家就决定,利用字节中闲置的最高位编入新的符号。比如,法语中的é的编码为130(二进制10000010)。这样一来,这些欧洲国家使用的编码体系,可以表示最多256个符号。
但是,这里又出现了新的问题。不同的国家有不同的字母,因此,哪怕它们都使用256个符号的编码方式,代表的字母却不一样。比如,130在法语编码中代表了é,在希伯来语编码中却代表了字母Gimel (ג),在俄语编码中又会代表另一个符号。但是不管怎样,所有这些编码方式中,0—127表示的符号是一样的,不一样的只是128—255的这一段。
至于亚洲国家的文字,使用的符号就更多了,汉字就多达10万左右。一个字节只能表示256种符号,肯定是不够的,就必须使用多个字节表达一个符号。比如,简体中文常见的编码方式是GB2312,使用两个字节表示一个汉字,所以理论上最多可以表示256x256=65536个符号。
中文编码的问题需要专文讨论,这篇笔记不涉及。这里只指出,虽然都是用多个字节表示一个符号,但是GB类的汉字编码与后文的Unicode和UTF-8是毫无关系的。
3.Unicode
正如上一节所说,世界上存在着多种编码方式,同一个二进制数字可以被解释成不同的符号。因此,要想打开一个文本文件,就必须知道它的编码方式,否则用错误的编码方式解读,就会出现乱码。为什么电子邮件常常出现乱码?就是因为发信人和收信人使用的编码方式不一样。
可以想象,如果有一种编码,将世界上所有的符号都纳入其中。每一个符号都给予一个独一无二的编码,那么乱码问题就会消失。这就是Unicode,就像它的名字都表示的,这是一种所有符号的编码。
Unicode当然是一个很大的集合,现在的规模可以容纳100多万个符号。每个符号的编码都不一样,比如,U+0639表示阿拉伯字母Ain,U+0041表示英语的大写字母A,U+4E25表示汉字“严”。
4. Unicode的问题
需要注意的是,Unicode只是一个符号集,它只规定了符号的二进制代码,却没有规定这个二进制代码应该如何存储。
比如,汉字“严”的unicode是十六进制数4E25,转换成二进制数足足有15位(100111000100101),也就是说这个符号的表示至少需要2个字节。表示其他更大的符号,可能需要3个字节或者4个字节,甚至更多。
这里就有两个严重的问题,第一个问题是,如何才能区别unicode和ascii?计算机怎么知道三个字节表示一个符号,而不是分别表示三个符号呢?第二个问题是,我们已经知道,英文字母只用一个字节表示就够了,如果unicode统一规定,每个符号用三个或四个字节表示,那么每个英文字母前都必然有二到三个字节是0,这对于存储来说是极大的浪费,文本文件的大小会因此大出二三倍,这是无法接受的。
它们造成的结果是:1)出现了unicode的多种存储方式,也就是说有许多种不同的二进制格式,可以用来表示unicode。2)unicode在很长一段时间内无法推广,直到互联网的出现。
5.UTF-8
互联网的普及,强烈要求出现一种统一的编码方式。UTF-8就是在互联网上使用最广的一种unicode的实现方式。其他实现方式还包括UTF-16和UTF-32,不过在互联网上基本不用。重复一遍,这里的关系是,UTF-8是Unicode的实现方式之一。
UTF-8最大的一个特点,就是它是一种变长的编码方式。它可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度。
UTF-8的编码规则很简单,只有二条:
1)对于单字节的符号,字节的第一位设为0,后面7位为这个符号的unicode码。因此对于英语字母,UTF-8编码和ASCII码是相同的。
2)对于n字节的符号(n>1),第一个字节的前n位都设为1,第n+1位设为0,后面字节的前两位一律设为10。剩下的没有提及的二进制位,全部为这个符号的unicode码。
下表总结了编码规则,字母x表示可用编码的位。
Unicode符号范围 | UTF-8编码方式
(十六进制) | (二进制)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
下面,还是以汉字“严”为例,演示如何实现UTF-8编码。
已知“严”的unicode是4E25(100111000100101),根据上表,可以发现4E25处在第三行的范围内(0000 0800-0000 FFFF),因此“严”的UTF-8编码需要三个字节,即格式是“1110xxxx 10xxxxxx 10xxxxxx”。然后,从“严”的最后一个二进制位开始,依次从后向前填入格式中的x,多出的位补0。这样就得到了,“严”的UTF-8编码是“11100100 10111000 10100101”,转换成十六进制就是E4B8A5。
怎么编码的暂不关心,看方法我们发现最后字节都被写到Segment 链表中了,每一个Segment 存满8192字节后在链表尾再加入新的Segment 用内部的byte[]存放字节,重点看一下Segment 和SegmentPool
Segment writableSegment(int minimumCapacity) {
if (minimumCapacity < 1 || minimumCapacity > Segment.SIZE) throw new IllegalArgumentException();
/**
* 如果头等于空则从缓存里面取
*/
if (head == null) {
head = SegmentPool.take(); // Acquire a first segment.
return head.next = head.prev = head;
}
Segment tail = head.prev;
if (tail.limit + minimumCapacity > Segment.SIZE || !tail.owner) {
tail = tail.push(SegmentPool.take()); // Append a new empty segment to fill up.
}
return tail;
}
第一次调用这个方法的时候head 肯定为空,那么就会从SegmentPool的缓冲池里面取,此时缓冲池肯定也为空,看代码
static Segment take() {
synchronized (SegmentPool.class) {
/**
* 如果下一个不等于空那么拿到下一个对象,并将链表的下一个赋值给当前的next
*/
if (next != null) {
Segment result = next;
next = result.next;
// 赋值完后,将 result.next的索引指向取消
result.next = null;
// 每取出一次就将byteCount减去SIZE
byteCount -= Segment.SIZE;
return result;
}
}
// 当前的next对象为空则创建新对象
return new Segment(); // Pool is empty. Don't zero-fill while holding a
// lock.
}
static void recycle(Segment segment) {
// 如果对象的头尾都有指向则不能假如队伍
if (segment.next != null || segment.prev != null)
throw new IllegalArgumentException();
// 假如shared属性为true,则说明segment还有用处不能被存放
if (segment.shared)
return; // This segment cannot be recycled.
synchronized (SegmentPool.class) {
// 假如缓存超过最大值返回
if (byteCount + Segment.SIZE > MAX_SIZE)
return; // Pool is full.
// 重新记录缓存的大小
byteCount += Segment.SIZE;
// 把segment放入队伍头
segment.next = next;
// pos标记为1
segment.pos = segment.limit = 0;
// 当前的next设置为队列头元素
next = segment;
}
}
SegmentPool
就两个实现方法。
接着看Buffer类,Buffer持有segment链表的头,把数据先写到byte[]字节数组中形成缓存,那么最后怎么将字节写入的呢?那么肯定就是我们的flush方法了,进入该方法
@Override public void flush() throws IOException {
if (closed) throw new IllegalStateException("closed");
if (buffer.size > 0) {
sink.write(buffer, buffer.size);
}
sink.flush();
}
sink.write最后执行到这个方法
public void write(Buffer source, long byteCount) throws IOException {
//检查数据长度是否匹配
checkOffsetAndCount(source.size, 0, byteCount);
while (byteCount > 0) {
timeout.throwIfReached();
//得到链表的头
Segment head = source.head;
int toCopy = (int) Math.min(byteCount, head.limit - head.pos);
//开始写入数据
out.write(head.data, head.pos, toCopy);
head.pos += toCopy;
byteCount -= toCopy;
source.size -= toCopy;
//当把head的数据写wanle之后,接着写下一个Segment的数据
if (head.pos == head.limit) {
source.head = head.pop();
//将head放入缓存
SegmentPool.recycle(head);
}
}
}
其中out是FileOutputStream,最后调用sink.flush()辗转到FileOutputStream的flush将数据写入文件