该类继承自FilterReader类
无引入包
该类的类头注释如下:
* A character-stream reader that allows characters to be pushed back into the * stream.
大意如下:
含有回推功能的字符输入流
该类含有如下的成员变量:
回推缓冲区
private char[] buf;
缓冲区偏移量
private int pos;
该类含有如下的成员方法:
构造函数(规定输入流和缓冲区大小
public PushbackReader(Reader in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } this.buf = new char[size]; this.pos = size; }
构造函数(规定输入流,使用默认缓冲区大小
public PushbackReader(Reader in) { this(in, 1); }
流开启确认函数(只需检查缓冲区有效性
private void ensureOpen() throws IOException { if (buf == null) throw new IOException("Stream closed"); }
读取一个字符数据
public int read() throws IOException { synchronized (lock) { ensureOpen(); if (pos < buf.length)//检测当前缓冲区是否有东西,没有就直接从流中读取 return buf[pos++]; else return super.read(); } }
读取一个字符数组
public int read(char cbuf[], int off, int len) throws IOException { synchronized (lock) { ensureOpen(); try { if (len <= 0) { if (len < 0) { throw new IndexOutOfBoundsException(); } else if ((off < 0) || (off > cbuf.length)) { throw new IndexOutOfBoundsException(); } return 0; } int avail = buf.length - pos;//缓冲区有效大小 if (avail > 0) {//缓冲区有效 if (len < avail)//需求字符数小于缓冲区有效数量,可直接从缓冲区读取 avail = len; System.arraycopy(buf, pos, cbuf, off, avail); pos += avail; off += avail; len -= avail; } if (len > 0) {//如果缓冲区读完还需要数据 len = super.read(cbuf, off, len); if (len == -1) { return (avail == 0) ? -1 : avail; } return avail + len; } return avail;//返回实际读取数据量 } catch (ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); } } }
回推一个字符(传入Ascii码
public void unread(int c) throws IOException { synchronized (lock) { ensureOpen(); if (pos == 0) throw new IOException("Pushback buffer overflow"); buf[--pos] = (char) c; } }
回推一个字符数组(需要检查回推长度和缓冲剩余长度
public void unread(char cbuf[], int off, int len) throws IOException { synchronized (lock) { ensureOpen(); if (len > pos) throw new IOException("Pushback buffer overflow"); pos -= len; System.arraycopy(cbuf, off, buf, pos, len); } }
回推整个字符数组
public void unread(char cbuf[]) throws IOException { unread(cbuf, 0, cbuf.length); }
返回当前流是否可以被读取信息(流开启且仍有数据
public boolean ready() throws IOException { synchronized (lock) { ensureOpen(); return (pos < buf.length) || super.ready(); } }
标记设置(该类不支持标记,所以没啥用
public void mark(int readAheadLimit) throws IOException { throw new IOException("mark/reset not supported"); }
回滚(也没用
public void reset() throws IOException { throw new IOException("mark/reset not supported"); }
检测该类是否支持标记(不支持啊
public boolean markSupported() { return false; }
跳过后续的n个字符读取
public long skip(long n) throws IOException { if (n < 0L) throw new IllegalArgumentException("skip value is negative"); synchronized (lock) {//防止读取跳过的字符 ensureOpen(); int avail = buf.length - pos;//先跳缓冲区,再跳流中字符 if (avail > 0) { if (n <= avail) { pos += n; return n; } else { pos = buf.length; n -= avail; } } return avail + super.skip(n); } }
关闭流
public void close() throws IOException { super.close(); buf = null; }
该类就是PushbackInputStream的字符流类,具体分析见该类