1、案例代码
public static void main(String[] args) throws IOException {
//字符缓冲流
BufferedReader bufferedReader=new BufferedReader(new FileReader
(new File("H:\ioText\b.txt")),8);
//存储读取的数据
char[] charsRead=new char[5];
//读取数据
bufferedReader.read(charsRead);
//遍历并输出charsRead
for (char c:charsRead){
System.out.println(c);
}
}
2、通过源码(部分)分析案例
a、第一次读取
public class BufferedReader extends Reader {
private Reader in;//字符流
private char cb[];//缓冲区
private int nChars, nextChar;//nChars缓冲区可读字符数,nextChar下一个字符位置
private static final int INVALIDATED = -2;
private static final int UNMARKED = -1;
private int markedChar = UNMARKED;
private int readAheadLimit = 0;
private boolean skipLF = false;
private boolean markedSkipLF = false;
private static int defaultCharBufferSize = 8192;//缓冲区默认大小
private static int defaultExpectedLineLength = 80;
//案例调用的构造方法
public BufferedReader(Reader in, int sz) {
//调用父类构造
super(in);
//判断缓冲区大小是否正常
if (sz <= 0)
throw new IllegalArgumentException("Buffer size <= 0");
//用户传入的字符流
this.in = in;
//给缓冲区指定空间大小(案例指定为8)
cb = new char[sz];
//缓冲区可读字符数和下一个字符位置初始化为0
nextChar = nChars = 0;
}
//读取数据
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;
}
//调用read1方法进行读取(真正读取数据的方法是read1方法)
int n = read1(cbuf, off, len);
if (n <= 0) return n;
//将之前没处理完的数据复制到自定以数组charsRead再次调用read1方法读取
while ((n < len) && in.ready()) {
int n1 = read1(cbuf, off + n, len - n);
if (n1 <= 0) break;
n += n1;
}
return