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 。