將現有字節數組包裝為 InputStream,支持標準流讀取接口(read、skip、mark/reset)。不涉及擴容,底層數組只讀,線程安全(方法 synchronized)。
protected byte buf[]; // 數據源數組
protected int pos; // 下一讀取索引
protected int mark = 0; // 標記索引
protected int count; // 數據有效長度
// 完整數組
public ByteArrayInputStream(byte[] buf) {
this.buf = buf; this.pos = 0; this.count = buf.length;
}
// 切片視圖:offset 起始,length 長度(不超過數組邊界)
public ByteArrayInputStream(byte[] buf, int offset, int length) {
this.buf = buf; 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;
}
public synchronized int read(byte[] b, int off, int len) {
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;
}
public synchronized long skip(long n) {
long k = count - pos;
if (n < k) k = n < 0 ? 0 : n;
pos += k; return k;
}
public boolean markSupported() { return true; }
public synchronized void mark(int readAheadLimit) { mark = pos; }
public synchronized void reset() { pos = mark; }
readAheadLimit 參數無實際限制(內存數組隨時可讀),標記即記錄當前 pos。
byte[] letters = "abcdefghijklmnopqrstuvwxyz".getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(letters);
// 讀前 5 字節:a b c d e
for (int i=0; i<5; i++) System.out.printf("%d: 0x%s%n", i, Integer.toHexString(in.read()));
in.mark(0); // 標記 f 位置
in.skip(5); // 跳過 f g h i j
byte[] buf = new byte[5];
in.read(buf); // 讀 k l m n o
System.out.println(new String(buf)); // klmno
in.reset(); // 回退到 f
in.read(buf); // 讀 f g h i j
System.out.println(new String(buf)); // fghij
ByteArrayInputStream 是字節數組到輸入流的零拷貝適配器,mark/reset 完美支持隨機訪問。常用於:單元測試模擬流、協議解析預讀、內存數據流式處理。注意:close() 無實際效果,數組生命周期由外部管理。