个人|java源码阅读系列-BufferReader

BufferReader源码 现在我们看是阅读io包下的源码.

先看开始的注释

/** * Reads text from a character-input stream, buffering characters so as to * provide for the efficient reading of characters, arrays, and lines.

【个人|java源码阅读系列-BufferReader】从字符流输入读取文本,缓冲字符作为字符、数组和行为。

首先我们知道BufferReader的中文名叫缓存字符输入流。顾名思义,就是为字符的输入添加缓冲功能。
下面是源码字符、数组和行的有效读取。
public class BufferedReader extends Reader {private Reader in; private char cb[]; private int nChars, nextChar; }

BufferdeReader继承了Reader类,有Reader类型的变量in,字符数组cb[],两个整形nChars和nextChar.

构造方法 第一种:
public BufferedReader(Reader in, int sz) { super(in); if (sz <= 0) throw new IllegalArgumentException("Buffer size <= 0"); this.in = in; cb = new char[sz]; nextChar = nChars = 0;

}


这里调用了父类的构造方法,直接返回Reader对象
第二种:
public BufferedReader(Reader in) { this(in, defaultCharBufferSize); }


其实我们看到这两个不同是就是,一个是自己设定缓存区大小,一个是默认大小
默认的defaultCharBufferSize是8192,也就是2的13次幂.

其他方法 确保流没有关闭
/** Checks to make sure that the stream has not been closed */ private void ensureOpen() throws IOException { if (in == null) throw new IOException("Stream closed"); }

如果下一个字符是换行符,则跳过它
private void fill() throws IOException { int dst; if (markedChar <= UNMARKED) { /* No mark */ dst = 0; } else { /* Marked */ int delta = nextChar - markedChar; if (delta >= readAheadLimit) { /* Gone past read-ahead limit: Invalidate mark */ markedChar = INVALIDATED; readAheadLimit = 0; dst = 0; } else { if (readAheadLimit <= cb.length) { /* Shuffle in the current buffer */ System.arraycopy(cb, markedChar, cb, 0, delta); markedChar = 0; dst = delta; } else { /* Reallocate buffer to accommodate read-ahead limit */ char ncb[] = new char[readAheadLimit]; System.arraycopy(cb, markedChar, ncb, 0, delta); cb = ncb; markedChar = 0; dst = delta; } nextChar = nChars = delta; } }int n; do { n = in.read(cb, dst, cb.length - dst); } while (n == 0); if (n > 0) { nChars = dst + n; nextChar = dst; } }

代码用的是System.arraycopy方法,这个和ArrayList差不多呵.



    推荐阅读