首页 > 编程语言 > 详细

javaIO——LineNumberReader

时间:2019-08-19 16:18:40      阅读:90      评论:0      收藏:0      [点我收藏+]

  LineNumberReader 是java字符流中的一员,它继承自 BufferedReader,只是在 BufferedReader 基础上,提供了对当前流位置所在文本行的标记记录。先来看看定义:

    技术分享图片

  可以看出,其定义了一个 lineNumber 字段对当前所在行进行记录。注释中红框说明了:setLineNumber(int) 方法仅仅是改变从 getLineNumber() 返回的值而已,而不会改变流的当前位置。也就是说 lineNumber 只是一个记录值,并不影响流的读取过程。

  下面贴一下 read 方法:

    

    public int read() throws IOException {
        synchronized (lock) {
            int c = super.read();
            if (skipLF) {
                if (c == ‘\n‘)
                    c = super.read();
                skipLF = false;
            }
            switch (c) {
            case ‘\r‘:
                skipLF = true;
            case ‘\n‘:          /* Fall through */
                lineNumber++;
                return ‘\n‘;
            }
            return c;
        }
    }


    public int read(char cbuf[], int off, int len) throws IOException {
        synchronized (lock) {
            int n = super.read(cbuf, off, len);

            for (int i = off; i < off + n; i++) {
                int c = cbuf[i];
                if (skipLF) {
                    skipLF = false;
                    if (c == ‘\n‘)
                        continue;
                }
                switch (c) {
                case ‘\r‘:
                    skipLF = true;
                case ‘\n‘:      /* Fall through */
                    lineNumber++;
                    break;
                }
            }

            return n;
        }
    }



    public String readLine() throws IOException {
        synchronized (lock) {
            String l = super.readLine(skipLF);
            skipLF = false;
            if (l != null)
                lineNumber++;
            return l;
        }
    }

  可以看出,都是通过调用父类 BufferedReader 的 对应方法,然后根据对换行符的判断,进行行数的增长操作。值得注意的是,行数记录的是外部使用者真正获得数据的流位置所在的行,而不是缓存位置所在的行

  总结起来就是,LineNumberReader 是可以记录当前数据所在行号的字符缓冲输入流。

javaIO——LineNumberReader

原文:https://www.cnblogs.com/coding-one/p/11377347.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!