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

Java IO 字節數組輸出流:ByteArrayOutputStream 源碼與實戰

     編輯:Java 相關知識

ByteArrayOutputStream 定位

將字節數據寫入內存字節數組,緩衝區自動擴容(默認 32 字節,倍增策略)。最終通過 toByteArray() 或 toString() 獲取結果。常用於:內存組包、測試替換文件流、序列化緩衝。

繼承體系與核心字段


public class ByteArrayOutputStream extends OutputStream {
    protected byte buf[];  // 底層存儲數組
    protected int count;   // 有效字節數
}

關鍵源碼邏輯

擴容策略:ensureCapacity → grow


private void ensureCapacity(int minCapacity) {
    if (minCapacity - buf.length > 0) grow(minCapacity);
}
private void grow(int minCapacity) {
    int old = buf.length;
    int newCap = old << 1; // 倍增
    if (newCap - minCapacity < 0) newCap = minCapacity;
    if (newCap < 0) newCap = Integer.MAX_VALUE; // 防溢出
    buf = Arrays.copyOf(buf, newCap);
}

寫入操作


public synchronized void write(int b) {
    ensureCapacity(count + 1);
    buf[count++] = (byte)b;
}
public synchronized void write(byte[] b, int off, int len) {
    ensureCapacity(count + len);
    System.arraycopy(b, off, buf, count, len);
    count += len;
}

輸出與重置


public synchronized void writeTo(OutputStream out) throws IOException {
    out.write(buf, 0, count); // 直接輸出到另一流
}
public synchronized void reset() { count = 0; } // 重用緩衝區
public synchronized byte[] toByteArray() { return Arrays.copyOf(buf, count); }
public synchronized String toString() { return new String(buf, 0, count); }

實戰示例


ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(0x41); baos.write(0x42); baos.write(0x43); // ABC
baos.write(new byte[]{0x64,0x65,0x66,0x67,0x68}, 0, 5); // defgh
System.out.println(baos); // ABCdefgh
System.out.println(baos.size()); // 8

byte[] data = baos.toByteArray(); // 獲取副本
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
baos.writeTo(baos2); // 複製到另一流

總結

ByteArrayOutputStream 以動態字節數組實現內存字節累積,synchronized 保證線程安全,reset() 支持緩衝區重用減少 GC。性能敏感場景可預估大小用 new ByteArrayOutputStream(initialSize) 減少擴容開銷。

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