首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java IO 字節數組輸入流:ByteArrayInputStream 源碼與實戰

     編輯:Java 相關知識

ByteArrayInputStream 定位

將現有字節數組包裝為 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;
}

Mark/Reset 機制


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() 無實際效果,數組生命周期由外部管理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved