java.io.ByteArrayInputStream 源码分析

ByteArrayInputStream 包含一个内部缓冲区,该缓冲区包含从流中读取的字节。

成员变量

    //由该流的创建者提供的 byte 数组。
    protected byte buf[];

    //要从输入流缓冲区中读取的下一个字符的索引。
    protected int pos;

    //流中当前的标记位置。
    protected int mark = 0;

    //比输入流缓冲区中最后一个有效字符的索引大一的索引。
    protected int count;

构造参数 提供一个byte数组

    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

构造参数 

buf - 输入缓冲区。

offset - 缓冲区中要读取的第一个字节的偏移量。

length - 从缓冲区中读取的最大字节数。

    public ByteArrayInputStream(byte buf[], int offset, int length) {
        this.buf = buf;
        this.pos = offset;
        this.count = Math.min(offset + length, buf.length);
        this.mark = offset;
    }

读取一个字节

  public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }

读取多个字节

    public synchronized int read(byte b[], int off, int len) {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        }
        //已经读完
        if (pos >= count) {
            return -1;
        }
        //判断len的大小是否超过缓冲区剩余可读字节
        int avail = count - pos;
        if (len > avail) {
            //将len设置为最后可读全部字节大小
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        System.arraycopy(buf, pos, b, off, len);
        pos += len;
        return len;
    }

跳过N个字节

    public synchronized long skip(long n) {
        long k = count - pos;
        if (n < k) {
            k = n < 0 ? 0 : n;
        }

        pos += k;
        return k;
    }

返回可从此输入流读取(或跳过)的剩余字节数。

    public synchronized int available() {
        return count - pos;
    }

设置mark与reset

    public void mark(int readAheadLimit) {
        mark = pos;
    }

    public synchronized void reset() {
        pos = mark;
    }
原文地址:https://www.cnblogs.com/daxin/p/3772931.html