JAVA基础知识之ByteArrayInputStream流

一、ByteArrayInputStream流定义

     API说明:ByteArrayInputStream包含一个内部缓冲区,其中包含可以从流中读取的字节,内部计数器跟踪read方法提供的下一个字节,关闭ByteArrayInputStream流无效,关闭流后调用类的方法不会有异常产生

二、ByteArrayInputStream流实例域

 /**
     * 字节数组缓冲区,buf[0]到buf[count-1]是可以从流中读取的字节,buf[pos]是读取的下一字节
     */
    protected byte buf[];

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

    /**
     * 流中当前标记的位置,默认标记为0,可以通过mark方法设置新的标记点,而后通过reset方法将当前位置设置为标记点
     * 从标记点开始读取数据
     *
     * @since   JDK1.1
     */
    protected int mark = 0;

    /**
     * 索引结束位置+1,不大于缓冲区的长度
     */
    protected int count;

三、ByteArrayInputStream流构造函数

 /**
     * 使用指定字节数组创建ByteArrayInputStream流,字节数组为流的缓冲区,
     * 当前位置索引pos初始值是0,索引结束位置count的是buf的长度
     */
    public ByteArrayInputStream(byte buf[]) {
        this.buf = buf;
        this.pos = 0;
        this.count = buf.length;
    }

    /**
     * 使用指定的数组创建ByteArrayInputStream流
     * 目标数组为流的缓冲区数组
     * 缓冲区当前起始位置变量值为off
     * 缓冲区的索引结束位置为:buf.length和off+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流方法

1)read():从此输入流中读取下一个字节并返回,当流到达末尾时,返回-1

 /**
     * 从此输入流中读取下一个字节并返回
     * 当流到达末尾时,返回-1
     * 注意& 0xff是字节的补码操作,暂时不用理会
     */
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }

2)read(byte b[], int off, int len) : 从输入流中读取最多len个字节到目标数组中,返回实际读取的字节数

   /**
     * 从输入流中读取最多len个字节到目标数组中,返回实际读取的字节数
     * 当缓冲区中剩余字符数小于len个字节时,读取缓冲区剩余字符数
     * 当剩余字符数大于len个字节时,读取len个字节
     */
    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;
    }

3)close() :  关闭流无效,关闭后调用其它方法不会有异常

    /**
     * 关闭流无效,关闭后调用其它方法不会有异常
     */
    public void close() throws IOException {
    }

五、ByteArrayInputStream流的作用

     暂时不理解具体作用,不清楚什么时候会用到该流,因为实际项目暂未用到,故先了解其功能即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值