字节数组流类包括ByteArrayInputStream、ByteArrayOutputStream。
首先理解ByteArrayInputStream,该类继承InputStream,覆盖了父类的read方法。看一下,ByteArrayInputSream的源码:
//构造函数,根据构造函数可以看出,ByteArrayInputStream的操作对象是字节数组,在对
//象内部存在一个buf对象,用来缓存字节数组对象。
public ByteArrayInputStream(byte buf[]) {
this.buf = buf;
this.pos = 0;
this.count = buf.length;
}
//read方法,逐个读取数组,返回字节数组中一个元素(一个字节)
public synchronized int read() {
return (pos < count) ? (buf[pos++] & 0xff) : -1;
}
//read方法 多态,将对象中的字节数组复制到b[]中,并返回复制的个数
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;
}
ByteArrayOutputStream类,继承了OutputStream类,查看ByteArrayOutputStream源码,理解若干重要方法的使用:
//构造函数,实例化一个字节数组,默认长度为32
public ByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: "
+ size);
}
buf = new byte[size];
}
//write方法,将字节数组b[]复制到对象中的buf中,因此在设置buf长度时要大于总的字节数组长度
public synchronized void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) - b.length > 0)) {
throw new IndexOutOfBoundsException();
}
ensureCapacity(count + len);
System.arraycopy(b, off, buf, count, len);//复制
count += len;
}
//获取字符串,线程同步
public synchronized String toString() {
return new String(buf, 0, count);
}
//根据编码类型,获取字符串,默认编码类型是“ISO-8859-1”
public synchronized String toString(String charsetName)
throws UnsupportedEncodingException
{
return new String(buf, 0, count, charsetName);
}
//将字节数组复制到其它字节数组输出流中的字节数组中
public synchronized void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
根据以上源码理解,可以得出字节数组流的操作对象就是字节数组,当需要对字符串、数据库中的内容等进行传输时,需要将它们转换成流,这时,字节数组流就最合适了。