1、API说明
2、实例域
private String str;
private int length;
private int next = 0;
private int mark = 0;
3、构造函数
public StringReader(String s) {
this.str = s;
this.length = s.length();
}
4、常用API
- read():从流中读取单个字符,若到文件末尾则返回 -1
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
if (next >= length)
return -1;
return str.charAt(next++);
}
}
- read(char cbuf[], int off, int len):读取最多len个字节到目标数组中,从目标数组的下标off开始存储,返回实际读取的字节数
public int read(char cbuf[], int off, int len) throws IOException {
synchronized (lock) {
ensureOpen();
if ((off < 0) || (off > cbuf.length) || (len < 0) ||
((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}
if (next >= length)
return -1;
int n = Math.min(length - next, len);
str.getChars(next, next + n, cbuf, off);
next += n;
return n;
}
}
- close() :关闭流无效,关闭后调用该类其它方法会报异常
public void close() {
str = null;
}