Java IO之ByteArrayInputStream源码分析

01.ByteArrayInputStream介绍

在这里插入图片描述
ByteArrayInputStream是字节数组输入流,继承与InputStream。

它的内部缓冲区就是一个字节数组,而ByteArrayInputStream本质就是通过字节数组来实现的。

流的来源或目的地并不一定是文件,也可以是内存中的一块空间,例如一个字节数组。ByteArrayInputStream就是将字节数组当作流输入来源类。

02.源码分析

在这里插入图片描述

// 保存字节输入流数据的字节数组
protected byte buf[];
 // 下一个会被读取的字节的索引
protected int pos;
// 流中当前标记的索引
protected int mark = 0;
// 字节流的长度
protected int count;
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;
    }
// 读取下一个字节
public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }

// 将“字节流的数据写入到字节数组b中”
  // off是“字节数组b的偏移地址”,表示从数组b的off开始写入数据
  // 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;
    }

// 跳过“字节流”中的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;
    }

public boolean markSupported() {
        return true;
    }

设置流中的当前标记位置。默认将ByteArrayInputStream对象标记在零位置。通过此方法可以将它们标记在缓冲区中的另一个*位置
public void mark(int readAheadLimit) {
        mark = pos;
    }

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

public void close() throws IOException {
    }

ByteArrayInputStream实际上是通过“字节数组”去保存数据。
(01) 通过ByteArrayInputStream(byte buf[]) 或 ByteArrayInputStream(byte buf[], int offset, int length) ,我们可以根据buf数组来创建字节流对象。
(02) read()的作用是从字节流中“读取下一个字节”。
(03) 关闭ByteArrayInputStream没有任何效果。 在关闭流之后,可以调用此类中的方法,而不生成IOException 。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值