字節數組流類包括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);
}
根據以上源碼理解,可以得出字節數組流的操作對象就是字節數組,當需要對字符串、數據庫中的內容等進行傳輸時,需要將它們轉換成流,這時,字節數組流就最合適了。