记录一次ByteArrayInputStream总是读不到数据的问题

69 阅读1分钟
需要将ByteArrayInputStream转为Base64,在读取时明明有数据却读不到数据,改了各种方式。debug发现pos的位置已经到了最后。
需要重置才可以读到数据。
inputStream.reset();

public class ByteArrayInputStream extends InputStream {
    protected byte buf[];//输入流的源
    protected int pos;//输入流当前位置===踩点
    protected int mark = 0;//标记的位置
    protected int count;//流的最大位置
    //返回当前位置的字节,并 pos 加 1
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }
    //将流中的自己赋值到 字节数组 b 中,并更新流的位置
    public synchronized int read(byte b[], int off, int len) {...}
    //跳过 n 个字节
    public synchronized long skip(long n) {}
    //返回还有多少字节(准确)
    public synchronized int available() {}
    public void mark(int readAheadLimit) {
        mark = pos;//标记当前流位置,以便后面的 reset
    }
    public synchronized void reset() {
        pos = mark;//重置流到 mark 位置====重置当前位置到开始
    }
    //因为 ByteArrayInputStream 流对其它资源无任何影响,所以不用任何操作
    public void close() throws IOException {}
    
    //用 buf[] 数组初始化流
    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;
    }
}