ByteArrayOutputStream constructor

ByteArrayOutputStream([
  1. int initialCapacity = _defaultInitialCapacity
])

An OutputStream that writes to a growable internal byte buffer.

ByteArrayOutputStream provides an in-memory output sink similar to Java's ByteArrayOutputStream. It allows binary data to be written sequentially and later retrieved as a single Uint8List for processing, storage, or transmission.

This stream grows automatically as more bytes are written, making it suitable for dynamic or unknown-length binary outputs.


🔧 Example:

final stream = ByteArrayOutputStream();
stream.writeByte(104); // h
stream.writeByte(105); // i

final result = stream.toBytes();
print(String.fromCharCodes(result)); // hi

✅ Use Cases:

  • Buffering binary content before sending to a file or network.
  • Serializing data in memory.
  • Mocking writable streams during testing.

Creates a new ByteArrayOutputStream with an optional initialCapacity. If not provided, defaults to 32 bytes.

The internal buffer will automatically grow when needed.

Implementation

ByteArrayOutputStream([int initialCapacity = _defaultInitialCapacity])
    : _buffer = Uint8List(initialCapacity);