將字節數據寫入內存字節數組,緩衝區自動擴容(默認 32 字節,倍增策略)。最終通過 toByteArray() 或 toString() 獲取結果。常用於:內存組包、測試替換文件流、序列化緩衝。
public class ByteArrayOutputStream extends OutputStream {
protected byte buf[]; // 底層存儲數組
protected int count; // 有效字節數
}
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) 減少擴容開銷。