Java IO类库之字节数组输入流ByteArrayInputStream

一、ByteArrayInputStream字节数组输入流介绍

    ByteArrayInputStream是字节数组输入流,继承自InputStream。它的内部包含一个缓冲区,是一个字节数组,缓冲数组用于保存从流中读取的字节数据,ByteArrayInputStream的内部定义了一个计数器pos,被用于定位read()方法要读取的下一个字节。

二、ByteArrayInputStream源码分析

1 - 成员变量
public
class ByteArrayInputStream extends InputStream {

    //内部缓冲数组,用于保存字节输入流数据
    protected byte buf[];

    //待读取字节的索引
    protected int pos;

    //字节输入流标记索引
    protected int mark = 0;

    //缓冲区有效字节数,等于缓冲区最后一个有效字节的下一个下标
    protected int count;
2、构造方法
    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.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;
    }

ByteArrayInputStream有两个构造函数,ByteArrayInputStream(byte buf[])主要通过传入一个字节数组buf初始化ByteArrayInputStream的一些成员变量,生成一个字节数组输入流,ByteArrayInputStream(byte buf[], int offset, int length)通过传入offset和字节数组长度length初始化当前字节流,第二种构造函数还额外对读取起点做了标记,并提供标记回滚。

3 - 成员方法

    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;
        }

        int avail = count - pos;
        if (len > avail) {
            len = avail;
        }
        if (len <= 0) {
            return 0;
        }
        System.arraycopy(buf, pos, b, off, len);
        pos += len;
        return len;
    }

    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;
    }

    public boolean markSupported() {
        return true;
    }

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

    public synchronized void reset() {
        pos = mark;
    }

    public void close() throws IOException {
    }

ByteArrayInputStream字节数组输入流的各个成员方法逻辑非常简单,都是基于对内部缓冲数组buf以及数组中各种标记位pos、mark,count的操作实现的,这里就不再进行分析了。

 

转载于:https://my.oschina.net/zhangyq1991/blog/1860640

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值