java io CharArrayReader源码分析

目录

简介

字段buf,pos,markedPos,count,两个构造函数

ensureOpen方法,2个read方法,skip方法

方法ready,markSupported,mark,reset,close


简介

/**
 * 这个类实现了一个字符缓冲区,它可以用作字符输入流。
 *
 * @author      Herb Jellinek
 * @since       JDK1.1
 */
public class CharArrayReader extends Reader 

字段buf,pos,markedPos,count,两个构造函数

    /** 字符缓冲 */
    protected char buf[];

    /** 当前缓冲区位置 */
    protected int pos;

    /** 标记在缓冲区中的位置。*/
    protected int markedPos = 0;

    /**
     *  缓冲区末尾的索引。在此索引处或索引之外没有有效数据。
     */
    protected int count;

    /**
     * 从指定的字符数组创建CharArrayReader。
     * 
     * @param buf       Input buffer (not copied)
     */
    public CharArrayReader(char buf[]) {
    	// 设置buf,设置pos为0,count为buf的长度
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    /**
     * 从指定的字符数组创建CharArrayReader。
     *
     * <p> 生成的reader将从给定的offset开始读取。
     * 可以从该读取器读取的char值的总数将是length或buf.length-offset,以较小的为准。
     *
     * @throws IllegalArgumentException
     *         If <tt>offset</tt> is negative or greater than
     *         <tt>buf.length</tt>, or if <tt>length</tt> is negative, or if
     *         the sum of these two values is negative.
     *
     * @param buf       Input buffer (not copied)
     * @param offset    Offset of the first char to read
     * @param length    Number of chars to read
     */
    public CharArrayReader(char buf[], int offset, int length) {
        if ((offset < 0) || (offset > buf.length) || (length < 0) ||
            ((offset + length) < 0)) {
            throw new IllegalArgumentException();
        }
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.markedPos = offset;
    }

ensureOpen方法,2个read方法,skip方法

    /** 检查以确保流没有被关闭  
     *   close时,buf设置为null */
    private void ensureOpen() throws IOException {
        if (buf == null)
            throw new IOException("Stream closed");
    }

    /**
     * 读取单个字符。
     *
     * @exception   IOException  If an I/O error occurs
     */
    public int read() throws IOException {
    	// 所有操作都对lock进行同步
        synchronized (lock) {
            ensureOpen();
            if (pos >= count)
                return -1;
            else
            	// 返回buf[pos],然后pos++
                return buf[pos++];
        }
    }

    /**
     * 将字符读入数组的一部分。
     * @param b  Destination buffer
     * @param off  Offset at which to start storing characters
     * @param len   Maximum number of characters to read
     * @return  The actual number of characters read, or -1 if
     *          the end of the stream has been reached
     *
     * @exception   IOException  If an I/O error occurs
     */
    public int read(char b[], int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if ((off < 0) || (off > b.length) || (len < 0) ||
                ((off + len) > b.length) || ((off + len) < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return 0;
            }

            if (pos >= count) {
                return -1;
            }
            // 读取长度为min(len,count-pos)
            if (pos + len > count) {
                len = count - pos;
            }
            if (len <= 0) {
                return 0;
            }
            // buf复制len个char到b
            System.arraycopy(buf, pos, b, off, len);
            pos += len;
            return len;
        }
    }

    /**
     * 跳过字符。返回跳过的字符数。
     *
     * <p>参数n可能是负数,即使在这种情况下超类Reader的skip方法抛出了异常。
     * 如果n是负的,那么这个方法不执行任何操作并返回0。
     *
     * @param n The number of characters to skip
     * @return       The number of characters actually skipped
     * @exception  IOException If the stream is closed, or an I/O error occurs
     */
    public long skip(long n) throws IOException {
        synchronized (lock) {
            ensureOpen();
             // 跳过长度为min(n,count-pos)
            if (pos + n > count) {
                n = count - pos;
            }
            if (n < 0) {
                return 0;
            }
            // 直接移动指针即可
            pos += n;
            return n;
        }
    }

方法ready,markSupported,mark,reset,close

    /**
     * 告知该流是否已准备好读取。字符数组读取器总是准备好被读取。
     *
     * @exception  IOException  If an I/O error occurs
     */
    public boolean ready() throws IOException {
        synchronized (lock) {
            ensureOpen();
            // 判断是否还有可读取的内容
            return (count - pos) > 0;
        }
    }

    /**
     * 告知此流是否支持mark()操作,它确实支持。
     */
    public boolean markSupported() {
        return true;
    }

    /**
     * 标记流中的当前位置。
     * 后续调用reset()将把流重新定位到此处。
     *
     * @param  readAheadLimit  Limit on the number of characters that may be
     *                         read while still preserving the mark.  Because
     *                         the stream's input comes from a character array,
     *                         there is no actual limit; hence this argument is
     *                         ignored.
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
        synchronized (lock) {
            ensureOpen();
            // 设置markedPos为pos,无视readAheadLimit
            markedPos = pos;
        }
    }

    /**
     * 将流重置为最近的标记,如果从未被标记过,到开头。
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void reset() throws IOException {
        synchronized (lock) {
            ensureOpen();
            // markedPos初始为0,后来为pos
            pos = markedPos;
        }
    }

    /**
     * 关闭流并释放与之关联的任何系统资源。
     * 一旦流被关闭,进一步的read()、ready()、mark()、reset()或skip()调用将抛出一个IOException。
     * 关闭以前关闭的流没有任何效果。
     */
    public void close() {
        buf = null;
    }

 


版权声明:本文为xushiyu1996818原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。