javaIO——LineNumberReader

  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 == '
')
                    c = super.read();
                skipLF = false;
            }
            switch (c) {
            case '
':
                skipLF = true;
            case '
':          /* Fall through */
                lineNumber++;
                return '
';
            }
            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 == '
')
                        continue;
                }
                switch (c) {
                case '
':
                    skipLF = true;
                case '
':      /* 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 是可以记录当前数据所在行号的字符缓冲输入流。

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