package java.io; public class ByteArrayInputStream extends InputStream { // 保存字節輸入流數據的字節數組 protected byte buf[]; // 下一個會被讀取的字節的索引 protected int pos; // 標記的索引 protected int mark = 0; // 字節流的長度 protected int count; // 構造函數:建立一個內容爲buf的字節流 public ByteArrayInputStream(byte buf[]) { // 初始化「字節流對應的字節數組爲buf」 this.buf = buf; // 初始化「下一個要被讀取的字節索引號爲0」 this.pos = 0; // 初始化「字節流的長度爲buf的長度」 this.count = buf.length; } // 構造函數:建立一個內容爲buf的字節流,而且是從offset開始讀取數據,讀取的長度爲length public ByteArrayInputStream(byte buf[], int offset, int length) { // 初始化「字節流對應的字節數組爲buf」 this.buf = buf; // 初始化「下一個要被讀取的字節索引號爲offset」 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; } // 保存當前位置。readAheadLimit在此處沒有任何實際意義 public void mark(int readAheadLimit) { mark = pos; } // 重置「字節流的讀取索引」爲「mark所標記的位置」 public synchronized void reset() { pos = mark; } public void close() throws IOException { } }