继承关系
public class StringBufferInputStream extends InputStream
基本属性
protected String buffer; //这是字节被读取的字符串。
protected int pos;//这是下一个字符从输入流缓存器读取的索引。
protected int count; //这是在输入数据流缓存器有效字符数。
构造函数
//这里构造函数初始化Buffer和count,他将创建一个字符串输入流中读取指定的字符串数据
public StringBufferInputStream(String s) {
this.buffer = s;
count = s.length();
}
其主要方法
我拷贝了JDK1.7中的源码来进行剖析
public synchronized int read() {
return (pos < count) ? (buffer.charAt(pos++) & 0xFF) : -1;
}//这里就是判断下一个字节的索引位置是否合法,合法的话就调用buffer.charAt()方法,
//读取从这个输入流数据的下一个字节,不合法则返回-1.
public synchronized int read(byte b[], int off, int len) {//从b[]数组的off位置读len的长度
if (b == null) {//先判断b[]是否为空
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {//判断off和len的合法性
throw new IndexOutOfBoundsException();
}
if (pos >= count) {//判断pos的合法性
return -1;
}
if (pos + len > count) {//简单的说就是如果读取长度大于剩下长度,那么只能读取剩下的len
len = count - pos;
}
if (len <= 0) {
return 0;
}
String s = buffer;
int cnt = len;
while (--cnt >= 0) {//循环读取字符串buffer中的字节,存到b[]数组中
b[off++] = (byte)s.charAt(pos++);
}
return len;
}
//跳过n个字符
public synchronized long skip(long n) {
if (n < 0) {
return 0;
}
if (n > count - pos) {
n = count - pos;
}
pos += n;
return n;
}
public synchronized int available() {
return count - pos;
}
public synchronized void reset() {
pos = 0;
}