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.

从字符流输入读取文本,缓冲字符作为字符、数组和行为。

 

首先我们知道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差不多呵.
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值