该类的无引入包
继承自Reader类
该类的类头注释如下:
* A character stream whose source is a string.
大意如下:
读取对象是字符串的字符读入流
该类含有如下的成员变量:
需要读取的字符串
private String str;
字符串长度
private int length;
读取位置偏移量
private int next = 0;
标记回溯点
private int mark = 0;
该类含有如下的成员方法:
构造函数(传入需要读取的字符串
public StringReader(String s) { this.str = s; this.length = s.length(); }
确认流开启(确认目标字符串存在
private void ensureOpen() throws IOException { if (str == null) throw new IOException("Stream closed"); }
读取出字符串的单个字符(返回编码值
public int read() throws IOException { synchronized (lock) { ensureOpen(); if (next >= length)//读取越界判定 return -1; return str.charAt(next++);//读取完后修改指针 } }
读取出字符串中多个字符(写入传入的数组,返回实际读取值
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; } }
跳过字符串后多个字符读取(返回实际跳过值
public long skip(long ns) throws IOException { synchronized (lock) { ensureOpen(); if (next >= length) return 0; // Bound skip by beginning and end of the source long n = Math.min(length - next, ns); n = Math.max(-next, n); next += n; return n; } }
检测当前流是否有效(调用上述的ensureOpen方法
public boolean ready() throws IOException { synchronized (lock) { ensureOpen(); return true; } }
是否支持标记(都设置了标记变量肯定支持啊
public boolean markSupported() { return true; }
标记当前位置(传入最大回滚距离
public void mark(int readAheadLimit) throws IOException { if (readAheadLimit < 0){ throw new IllegalArgumentException("Read-ahead limit < 0"); } synchronized (lock) { ensureOpen(); mark = next; } }
回滚到标记位置
public void reset() throws IOException { synchronized (lock) { ensureOpen(); next = mark; } }
关闭该读取流
public void close() { str = null; }
该类十分简单,主要通过调用String类中的一些方法和自己设置的回滚操作来完成,对于学习字符读入流可以从该类开始,可以尝试自己来写一个类似的面向字符串的字符读取流。