前面學習ByteArrayInputStream,了解了“輸入流”。接下來,我們學習與ByteArrayInputStream相對應的輸出流,即ByteArrayOutputStream。
本章,我們會先對ByteArrayOutputStream進行介紹,在了解了它的源碼之后,再通過示例來掌握如何使用它。
轉載請注明出處:http://www.cnblogs.com/skywang12345/p/io_03.html
ByteArrayOutputStream 介紹
ByteArrayOutputStream 是字節數組輸出流。它繼承於OutputStream。
ByteArrayOutputStream 中的數據被寫入一個 byte 數組。緩沖區會隨着數據的不斷寫入而自動增長。可使用 toByteArray() 和 toString() 獲取數據。
OutputStream 函數列表
我們來看看ByteArrayOutputStream的父類OutputStream的函數接口。
// 構造函數 OutputStream() void close() void flush() void write(byte[] buffer, int offset, int count) void write(byte[] buffer) abstract void write(int oneByte)
ByteArrayOutputStream 函數列表
// 構造函數 ByteArrayOutputStream() ByteArrayOutputStream(int size) void close() synchronized void reset() int size() synchronized byte[] toByteArray() String toString(int hibyte) String toString(String charsetName) String toString() synchronized void write(byte[] buffer, int offset, int len) synchronized void write(int oneByte) synchronized void writeTo(OutputStream out)
OutputStream和ByteArrayOutputStream源碼分析
OutputStream是ByteArrayOutputStream的父類,我們先看看OutputStream的源碼,然后再學ByteArrayOutputStream的源碼。
1. OutputStream.java源碼分析(基於jdk1.7.40)

1 package java.io; 2 3 public abstract class OutputStream implements Closeable, Flushable { 4 // 將字節b寫入到“輸出流”中。 5 // 它在子類中實現! 6 public abstract void write(int b) throws IOException; 7 8 // 寫入字節數組b到“字節數組輸出流”中。 9 public void write(byte b[]) throws IOException { 10 write(b, 0, b.length); 11 } 12 13 // 寫入字節數組b到“字節數組輸出流”中,並且off是“數組b的起始位置”,len是寫入的長度 14 public void write(byte b[], int off, int len) throws IOException { 15 if (b == null) { 16 throw new NullPointerException(); 17 } else if ((off < 0) || (off > b.length) || (len < 0) || 18 ((off + len) > b.length) || ((off + len) < 0)) { 19 throw new IndexOutOfBoundsException(); 20 } else if (len == 0) { 21 return; 22 } 23 for (int i = 0 ; i < len ; i++) { 24 write(b[off + i]); 25 } 26 } 27 28 public void flush() throws IOException { 29 } 30 31 public void close() throws IOException { 32 } 33 }
2. ByteArrayOutputStream 源碼分析(基於jdk1.7.40)

1 package java.io; 2 3 import java.util.Arrays; 4 5 public class ByteArrayOutputStream extends OutputStream { 6 7 // 保存“字節數組輸出流”數據的數組 8 protected byte buf[]; 9 10 // “字節數組輸出流”的計數 11 protected int count; 12 13 // 構造函數:默認創建的字節數組大小是32。 14 public ByteArrayOutputStream() { 15 this(32); 16 } 17 18 // 構造函數:創建指定數組大小的“字節數組輸出流” 19 public ByteArrayOutputStream(int size) { 20 if (size < 0) { 21 throw new IllegalArgumentException("Negative initial size: " 22 + size); 23 } 24 buf = new byte[size]; 25 } 26 27 // 確認“容量”。 28 // 若“實際容量 < minCapacity”,則增加“字節數組輸出流”的容量 29 private void ensureCapacity(int minCapacity) { 30 // overflow-conscious code 31 if (minCapacity - buf.length > 0) 32 grow(minCapacity); 33 } 34 35 // 增加“容量”。 36 private void grow(int minCapacity) { 37 int oldCapacity = buf.length; 38 // “新容量”的初始化 = “舊容量”x2 39 int newCapacity = oldCapacity << 1; 40 // 比較“新容量”和“minCapacity”的大小,並選取其中較大的數為“新的容量”。 41 if (newCapacity - minCapacity < 0) 42 newCapacity = minCapacity; 43 if (newCapacity < 0) { 44 if (minCapacity < 0) // overflow 45 throw new OutOfMemoryError(); 46 newCapacity = Integer.MAX_VALUE; 47 } 48 buf = Arrays.copyOf(buf, newCapacity); 49 } 50 51 // 寫入一個字節b到“字節數組輸出流”中,並將計數+1 52 public synchronized void write(int b) { 53 ensureCapacity(count + 1); 54 buf[count] = (byte) b; 55 count += 1; 56 } 57 58 // 寫入字節數組b到“字節數組輸出流”中。off是“寫入字節數組b的起始位置”,len是寫入的長度 59 public synchronized void write(byte b[], int off, int len) { 60 if ((off < 0) || (off > b.length) || (len < 0) || 61 ((off + len) - b.length > 0)) { 62 throw new IndexOutOfBoundsException(); 63 } 64 ensureCapacity(count + len); 65 System.arraycopy(b, off, buf, count, len); 66 count += len; 67 } 68 69 // 寫入輸出流outb到“字節數組輸出流”中。 70 public synchronized void writeTo(OutputStream out) throws IOException { 71 out.write(buf, 0, count); 72 } 73 74 // 重置“字節數組輸出流”的計數。 75 public synchronized void reset() { 76 count = 0; 77 } 78 79 // 將“字節數組輸出流”轉換成字節數組。 80 public synchronized byte toByteArray()[] { 81 return Arrays.copyOf(buf, count); 82 } 83 84 // 返回“字節數組輸出流”當前計數值 85 public synchronized int size() { 86 return count; 87 } 88 89 public synchronized String toString() { 90 return new String(buf, 0, count); 91 } 92 93 public synchronized String toString(String charsetName) 94 throws UnsupportedEncodingException 95 { 96 return new String(buf, 0, count, charsetName); 97 } 98 99 @Deprecated 100 public synchronized String toString(int hibyte) { 101 return new String(buf, hibyte, 0, count); 102 } 103 104 public void close() throws IOException { 105 } 106 }
說明:
ByteArrayOutputStream實際上是將字節數據寫入到“字節數組”中去。
(01) 通過ByteArrayOutputStream()創建的“字節數組輸出流”對應的字節數組大小是32。
(02) 通過ByteArrayOutputStream(int size) 創建“字節數組輸出流”,它對應的字節數組大小是size。
(03) write(int oneByte)的作用將int類型的oneByte換成byte類型,然后寫入到輸出流中。
(04) write(byte[] buffer, int offset, int len) 是將字節數組buffer寫入到輸出流中,offset是從buffer中讀取數據的起始偏移位置,len是讀取的長度。
(05) writeTo(OutputStream out) 將該“字節數組輸出流”的數據全部寫入到“輸出流out”中。
示例代碼
關於ByteArrayOutputStream中API的詳細用法,參考示例代碼(ByteArrayOutputStreamTest.java):
1 import java.io.IOException; 2 import java.io.OutputStream; 3 import java.io.ByteArrayOutputStream; 4 import java.io.ByteArrayInputStream; 5 6 /** 7 * ByteArrayOutputStream 測試程序 8 * 9 * @author skywang 10 */ 11 public class ByteArrayOutputStreamTest { 12 13 private static final int LEN = 5; 14 // 對應英文字母“abcddefghijklmnopqrsttuvwxyz” 15 private static final byte[] ArrayLetters = { 16 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 17 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A 18 }; 19 20 public static void main(String[] args) { 21 //String tmp = new String(ArrayLetters); 22 //System.out.println("ArrayLetters="+tmp); 23 24 tesByteArrayOutputStream() ; 25 } 26 27 /** 28 * ByteArrayOutputStream的API測試函數 29 */ 30 private static void tesByteArrayOutputStream() { 31 // 創建ByteArrayOutputStream字節流 32 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 33 34 // 依次寫入“A”、“B”、“C”三個字母。0x41對應A,0x42對應B,0x43對應C。 35 baos.write(0x41); 36 baos.write(0x42); 37 baos.write(0x43); 38 System.out.printf("baos=%s\n", baos); 39 40 // 將ArrayLetters數組中從“3”開始的后5個字節寫入到baos中。 41 // 即對應寫入“0x64, 0x65, 0x66, 0x67, 0x68”,即“defgh” 42 baos.write(ArrayLetters, 3, 5); 43 System.out.printf("baos=%s\n", baos); 44 45 // 計算長度 46 int size = baos.size(); 47 System.out.printf("size=%s\n", size); 48 49 // 轉換成byte[]數組 50 byte[] buf = baos.toByteArray(); 51 String str = new String(buf); 52 System.out.printf("str=%s\n", str); 53 54 // 將baos寫入到另一個輸出流中 55 try { 56 ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); 57 baos.writeTo((OutputStream)baos2); 58 System.out.printf("baos2=%s\n", baos2); 59 } catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 }
運行結果:
baos=ABC
baos=ABCdefgh
size=8
str=ABCdefgh
baos2=ABCdefgh
更多內容
3. java io系列02之 ByteArrayInputStream的簡介,源碼分析和示例(包括InputStream)
4. java io系列03之 ByteArrayOutputStream的簡介,源碼分析和示例(包括OutputStream)