一、CharArrayReader流定义
API说明:该类实现了一个可用作字符输入流的字符缓冲区,即该类可利用字符缓冲区当做字符输入流进行读取工作
二、CharArrayReader流的构造函数
1)从指定字符数组构造CharArrayReader流对象
/**
* 利用指定字符数组创建CharArrayReader对象
* 本质是将字符数组赋值给对象的字符缓冲区
*/
public CharArrayReader(char buf[]) {
this.buf = buf;
this.pos = 0;
this.count = buf.length;
}
构造流程图:
2)从指定字符数组构造CharArrayReader流对象,CharArrayReader流从偏移量offset开始读取,能读取的最大长度值可以是leng或者buf.leng-offset的最小值
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;
}
构造示例图:
三、CharArrayReader流的实例域
/** 字符缓冲区 */
protected char buf[];
/** 缓冲区当前位置 */
protected int pos;
/** 标记在缓冲区中的位置 */
protected int markedPos = 0;
/**
* 缓冲区结束的索引,该索引或者之外没有有效数据
* 即缓冲区的长度值
*/
protected int count;
四、CharArrayReader流的API
1)read():读取单个字符并返回,当读取到缓冲区末尾时,返回-1
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
if (pos >= count) //当前位置大于等于结束索引时,代表缓冲区内容已读取到尾部,返回-1
return -1;
else
return buf[pos++]; //直接换回缓冲区字符
}
}
2)read(char b[], int off, int len):读取最多len个字符到目标数组中,返回实际读取的字符数,当读取到缓冲区末尾时,返回-1
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个字节后超出界限的话,则只读当前位置到结束索引的字节
len = count - pos;
}
if (len <= 0) { //感觉此if多余
return 0;
}
System.arraycopy(buf, pos, b, off, len); //从字符缓冲区中读取len个字节到目标数组中
pos += len; //修改字符缓冲区当前位置
return len;
}
}
3)close():关闭流并释放与其相关的资源(),关闭后调用其方法会抛出IOException异常
/**
*关闭流并释放资源--本质是将缓冲区赋值为null,则该流其它方法都不能使用
*根本就没有调用过系统资源,因此关闭是无效的?但是一旦关闭在调用其他方法,就会抛异常
*/
public void close() {
buf = null;
}
/** 确保流不被关闭 */
private void ensureOpen() throws IOException {
if (buf == null)
throw new IOException("Stream closed");
}
四、CharArrayReader流的作用
从API说明以及其实例域和方法来看,其就是利用了一个字符数组创建字符缓冲区而后充当所谓的字符缓冲流进行字符读取工作,本质没有与底层的文件这些建立联系
对该流在网上进行过咨询,解释为该流可以作为临时的字符数组内存使用,运行结束后自动删除--因为个人暂未在实际项目中暂未使用到这个流,因此对此答案也无法确信,只能先理解其功能,至于具体的作用和什么时候使用,待以后了解了再补充