所引入的包和继承关系:
无引入包
继承自Reader类
类的作用注释:
/** * This class implements a character buffer that can be used as a * character-input stream. * * @author Herb Jellinek * @since JDK1.1 */
大意如下:
这个类是用于字符类型输入流的缓冲接口(真是简洁明了)
含有四个成员变量:
缓冲区数组:
protected char buf[];
当前读取位置:
protected int pos;
标记位置:
protected int markedPos = 0;
有效长度:
protected int count;
含有十一个方法:
构造函数(缓冲区直接接受传入的字符数组):
public CharArrayReader(char buf[]) { this.buf = buf; this.pos = 0; this.count = buf.length; }
构造函数(缓冲区接受传入的字符数组,但读取时不从头读取):
public CharArrayReader(char buf[], int offset, int length) { if ((offset < 0) || (offset > buf.length) || (length < 0) || ((offset + length) < 0)) { throw new IllegalArgumentException();//数组参数有效性验证 } this.buf = buf; this.pos = offset;//读取指针为传入位置 this.count = Math.min(offset + length, buf.length);//有效区间为传入数组长度和需要读取长度加上读取开始位置之间的较小值 this.markedPos = offset;//设置标记 }
确认缓冲区初始化:
private void ensureOpen() throws IOException { if (buf == null) throw new IOException("Stream closed"); }
从缓冲区读取数据(单个读取):
public int read() throws IOException { synchronized (lock) {//线程锁 ensureOpen(); if (pos >= count)//读取越界 return -1; else return buf[pos++];//返回值为读取字符的ascii码
} }}
从缓冲区读取数据(批量读取):
public int read(char b[], int off, int len) throws IOException { synchronized (lock) {//线程锁 ensureOpen(); if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {//有效性检查 throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } if (pos >= count) { return -1; } if (pos + len > count) {//需读取长度越界 len = count - pos; } if (len <= 0) { return 0; } System.arraycopy(buf, pos, b, off, len); pos += len; return len;//返回实际读取长度 } }
跳过后续的n个字符:
public long skip(long n) throws IOException { synchronized (lock) { ensureOpen(); if (pos + n > count) {//跳跃区间越界 n = count - pos; } if (n < 0) { return 0; } pos += n; return n; } }
读取有效性检查:
public boolean ready() throws IOException { synchronized (lock) { ensureOpen(); return (count - pos) > 0; } }
是否支持标记:
public boolean markSupported() { return true; }
设置标记(没看懂这个传入参数有啥用,完全没有调用,估计是覆写要求):
public void mark(int readAheadLimit) throws IOException { synchronized (lock) { ensureOpen(); markedPos = pos;//设置当前位置为标记位 } }
回归至标记处:
public void reset() throws IOException { synchronized (lock) { ensureOpen(); pos = markedPos; } }
关闭流(直接置空缓冲):
public void close() { buf = null; }
和前面的ByteArray类似,缓冲区只能一次将所需数据读入,不能重复装填缓冲区,当数据量大或数据批次多的时候不建议使用