我們以ByteArrayInputStream,拉開對字節類型的“輸入流”的學習序幕。
本章,我們會先對ByteArrayInputStream進行介紹,然后深入了解一下它的源碼,最后通過示例來掌握它的用法。
轉載請注明出處:http://www.cnblogs.com/skywang12345/p/io_02.html
ByteArrayInputStream 介紹
ByteArrayInputStream 是字節數組輸入流。它繼承於InputStream。
它包含一個內部緩沖區,該緩沖區包含從流中讀取的字節;通俗點說,它的內部緩沖區就是一個字節數組,而ByteArrayInputStream本質就是通過字節數組來實現的。
我們都知道,InputStream通過read()向外提供接口,供它們來讀取字節數據;而ByteArrayInputStream 的內部額外的定義了一個計數器,它被用來跟蹤 read() 方法要讀取的下一個字節。
InputStream 函數列表
// 構造函數 InputStream() int available() void close() void mark(int readlimit) boolean markSupported() int read(byte[] buffer) abstract int read() int read(byte[] buffer, int offset, int length) synchronized void reset() long skip(long byteCount)
ByteArrayInputStream 函數列表
// 構造函數 ByteArrayInputStream(byte[] buf) ByteArrayInputStream(byte[] buf, int offset, int length) synchronized int available() void close() synchronized void mark(int readlimit) boolean markSupported() synchronized int read() synchronized int read(byte[] buffer, int offset, int length) synchronized void reset() synchronized long skip(long byteCount)
InputStream和ByteArrayInputStream源碼分析
InputStream是ByteArrayInputStream的父類,我們先看看InputStream的源碼,然后再學ByteArrayInputStream的源碼。
1. InputStream.java源碼分析(基於jdk1.7.40)

1 package java.io; 2 3 public abstract class InputStream implements Closeable { 4 5 // 能skip的大小 6 private static final int MAX_SKIP_BUFFER_SIZE = 2048; 7 8 // 從輸入流中讀取數據的下一個字節。 9 public abstract int read() throws IOException; 10 11 // 將數據從輸入流讀入 byte 數組。 12 public int read(byte b[]) throws IOException { 13 return read(b, 0, b.length); 14 } 15 16 // 將最多 len 個數據字節從此輸入流讀入 byte 數組。 17 public int read(byte b[], int off, int len) throws IOException { 18 if (b == null) { 19 throw new NullPointerException(); 20 } else if (off < 0 || len < 0 || len > b.length - off) { 21 throw new IndexOutOfBoundsException(); 22 } else if (len == 0) { 23 return 0; 24 } 25 26 int c = read(); 27 if (c == -1) { 28 return -1; 29 } 30 b[off] = (byte)c; 31 32 int i = 1; 33 try { 34 for (; i < len ; i++) { 35 c = read(); 36 if (c == -1) { 37 break; 38 } 39 b[off + i] = (byte)c; 40 } 41 } catch (IOException ee) { 42 } 43 return i; 44 } 45 46 // 跳過輸入流中的n個字節 47 public long skip(long n) throws IOException { 48 49 long remaining = n; 50 int nr; 51 52 if (n <= 0) { 53 return 0; 54 } 55 56 int size = (int)Math.min(MAX_SKIP_BUFFER_SIZE, remaining); 57 byte[] skipBuffer = new byte[size]; 58 while (remaining > 0) { 59 nr = read(skipBuffer, 0, (int)Math.min(size, remaining)); 60 if (nr < 0) { 61 break; 62 } 63 remaining -= nr; 64 } 65 66 return n - remaining; 67 } 68 69 public int available() throws IOException { 70 return 0; 71 } 72 73 public void close() throws IOException {} 74 75 public synchronized void mark(int readlimit) {} 76 77 public synchronized void reset() throws IOException { 78 throw new IOException("mark/reset not supported"); 79 } 80 81 public boolean markSupported() { 82 return false; 83 } 84 }
2. ByteArrayInputStream.java源碼分析(基於jdk1.7.40)

1 package java.io; 2 3 public class ByteArrayInputStream extends InputStream { 4 5 // 保存字節輸入流數據的字節數組 6 protected byte buf[]; 7 8 // 下一個會被讀取的字節的索引 9 protected int pos; 10 11 // 標記的索引 12 protected int mark = 0; 13 14 // 字節流的長度 15 protected int count; 16 17 // 構造函數:創建一個內容為buf的字節流 18 public ByteArrayInputStream(byte buf[]) { 19 // 初始化“字節流對應的字節數組為buf” 20 this.buf = buf; 21 // 初始化“下一個要被讀取的字節索引號為0” 22 this.pos = 0; 23 // 初始化“字節流的長度為buf的長度” 24 this.count = buf.length; 25 } 26 27 // 構造函數:創建一個內容為buf的字節流,並且是從offset開始讀取數據,讀取的長度為length 28 public ByteArrayInputStream(byte buf[], int offset, int length) { 29 // 初始化“字節流對應的字節數組為buf” 30 this.buf = buf; 31 // 初始化“下一個要被讀取的字節索引號為offset” 32 this.pos = offset; 33 // 初始化“字節流的長度” 34 this.count = Math.min(offset + length, buf.length); 35 // 初始化“標記的字節流讀取位置” 36 this.mark = offset; 37 } 38 39 // 讀取下一個字節 40 public synchronized int read() { 41 return (pos < count) ? (buf[pos++] & 0xff) : -1; 42 } 43 44 // 將“字節流的數據寫入到字節數組b中” 45 // off是“字節數組b的偏移地址”,表示從數組b的off開始寫入數據 46 // len是“寫入的字節長度” 47 public synchronized int read(byte b[], int off, int len) { 48 if (b == null) { 49 throw new NullPointerException(); 50 } else if (off < 0 || len < 0 || len > b.length - off) { 51 throw new IndexOutOfBoundsException(); 52 } 53 54 if (pos >= count) { 55 return -1; 56 } 57 58 int avail = count - pos; 59 if (len > avail) { 60 len = avail; 61 } 62 if (len <= 0) { 63 return 0; 64 } 65 System.arraycopy(buf, pos, b, off, len); 66 pos += len; 67 return len; 68 } 69 70 // 跳過“字節流”中的n個字節。 71 public synchronized long skip(long n) { 72 long k = count - pos; 73 if (n < k) { 74 k = n < 0 ? 0 : n; 75 } 76 77 pos += k; 78 return k; 79 } 80 81 // “能否讀取字節流的下一個字節” 82 public synchronized int available() { 83 return count - pos; 84 } 85 86 // 是否支持“標簽” 87 public boolean markSupported() { 88 return true; 89 } 90 91 // 保存當前位置。readAheadLimit在此處沒有任何實際意義 92 public void mark(int readAheadLimit) { 93 mark = pos; 94 } 95 96 // 重置“字節流的讀取索引”為“mark所標記的位置” 97 public synchronized void reset() { 98 pos = mark; 99 } 100 101 public void close() throws IOException { 102 } 103 }
說明:
ByteArrayInputStream實際上是通過“字節數組”去保存數據。
(01) 通過ByteArrayInputStream(byte buf[]) 或 ByteArrayInputStream(byte buf[], int offset, int length) ,我們可以根據buf數組來創建字節流對象。
(02) read()的作用是從字節流中“讀取下一個字節”。
(03) read(byte[] buffer, int offset, int length)的作用是從字節流讀取字節數據,並寫入到字節數組buffer中。offset是將字節寫入到buffer的起始位置,length是寫入的字節的長度。
(04) markSupported()是判斷字節流是否支持“標記功能”。它一直返回true。
(05) mark(int readlimit)的作用是記錄標記位置。記錄標記位置之后,某一時刻調用reset()則將“字節流下一個被讀取的位置”重置到“mark(int readlimit)所標記的位置”;也就是說,reset()之后再讀取字節流時,是從mark(int readlimit)所標記的位置開始讀取。
示例代碼
關於ByteArrayInputStream中API的詳細用法,參考示例代碼(ByteArrayInputStreamTest.java):
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; /** * ByteArrayInputStream 測試程序 * * @author skywang */ public class ByteArrayInputStreamTest { private static final int LEN = 5; // 對應英文字母“abcddefghijklmnopqrsttuvwxyz” private static final byte[] ArrayLetters = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; public static void main(String[] args) { String tmp = new String(ArrayLetters); System.out.println("ArrayLetters="+tmp); tesByteArrayInputStream() ; } /** * ByteArrayInputStream的API測試函數 */ private static void tesByteArrayInputStream() { // 創建ByteArrayInputStream字節流,內容是ArrayLetters數組 ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters); // 從字節流中讀取5個字節 for (int i=0; i<LEN; i++) { // 若能繼續讀取下一個字節,則讀取下一個字節 if (bais.available() >= 0) { // 讀取“字節流的下一個字節” int tmp = bais.read(); System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp)); } } // 若“該字節流”不支持標記功能,則直接退出 if (!bais.markSupported()) { System.out.println("make not supported!"); return ; } // 標記“字節流中下一個被讀取的位置”。即--標記“0x66”,因為因為前面已經讀取了5個字節,所以下一個被讀取的位置是第6個字節” // (01), ByteArrayInputStream類的mark(0)函數中的“參數0”是沒有實際意義的。 // (02), mark()與reset()是配套的,reset()會將“字節流中下一個被讀取的位置”重置為“mark()中所保存的位置” bais.mark(0); // 跳過5個字節。跳過5個字節后,字節流中下一個被讀取的值應該是“0x6B”。 bais.skip(5); // 從字節流中讀取5個數據。即讀取“0x6B, 0x6C, 0x6D, 0x6E, 0x6F” byte[] buf = new byte[LEN]; bais.read(buf, 0, LEN); // 將buf轉換為String字符串。“0x6B, 0x6C, 0x6D, 0x6E, 0x6F”對應字符是“klmno” String str1 = new String(buf); System.out.printf("str1=%s\n", str1); // 重置“字節流”:即,將“字節流中下一個被讀取的位置”重置到“mark()所標記的位置”,即0x66。 bais.reset(); // 從“重置后的字節流”中讀取5個字節到buf中。即讀取“0x66, 0x67, 0x68, 0x69, 0x6A” bais.read(buf, 0, LEN); // 將buf轉換為String字符串。“0x66, 0x67, 0x68, 0x69, 0x6A”對應字符是“fghij” String str2 = new String(buf); System.out.printf("str2=%s\n", str2); } }
運行結果:
ArrayLetters=abcdefghijklmnopqrstuvwxyz
0 : 0x61
1 : 0x62
2 : 0x63
3 : 0x64
4 : 0x65
str1=klmno
str2=fghij
結果說明:
(01) ArrayLetters 是字節數組。0x61對應的ASCII碼值是a,0x62對應的ASCII碼值是b,依次類推...
(02) ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters); 這句話是創建“字節流bais”,它的內容就是ArrayLetters。
(03) for (int i=0; i<LEN; i++) ; 這個for循環的作用就是從字節流中讀取5個字節。每次調用bais.read()就從字節流中讀取一個字節。
(04) bais.mark(0); 這句話就是“設置字節流的標記”,此時標記的位置對應的值是0x66。
(05) bais.skip(5); 這句話是跳過5個字節。跳過5個字節后,對應的字節流中下一個被讀取的字節的值是0x6B。
(06) bais.read(buf, 0, LEN); 這句話是“從字節流中讀取LEN個數據寫入到buf中,0表示從buf的第0個位置開始寫入”。
(07) bais.reset(); 這句話是將“字節流中下一個被讀取的位置”重置到“mark()所標記的位置”,即0x66。
學完了ByteArrayInputStream輸入流。下面,我們學習與之對應的輸出流ByteArrayOutputStream。
更多內容
3. java io系列02之 ByteArrayInputStream的簡介,源碼分析和示例(包括InputStream)
4. java io系列03之 ByteArrayOutputStream的簡介,源碼分析和示例(包括OutputStream)