ByteArrayOutputStream class

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.
Inheritance

Constructors

ByteArrayOutputStream([int initialCapacity = _defaultInitialCapacity])
An OutputStream that writes to a growable internal byte buffer.

Properties

hashCode β†’ int
The hash code for this object.
no setterinherited
isClosed β†’ bool
Returns true if this stream has been closed.
no setterinherited
runtimeType β†’ Type
A representation of the runtime type of the object.
no setterinherited

Methods

checkClosed() β†’ void
Checks if the stream is closed and throws an exception if it is.
inherited
close() β†’ Future<void>
Closes this output stream and releases any system resources associated with this stream.
inherited
flush() β†’ Future<void>
Flushes this output stream and forces any buffered output bytes to be written out.
inherited
noSuchMethod(Invocation invocation) β†’ dynamic
Invoked when a nonexistent method or property is accessed.
inherited
reset() β†’ void
Resets the buffer to empty, discarding all written data.
size() β†’ int
Returns the current size of the buffer (number of bytes written).
toByteArray() β†’ Uint8List
Returns a copy of the current contents as a byte array.
toString([String encoding = 'utf-8']) β†’ String
Returns the current contents as a string using UTF-8 encoding.
override
write(List<int> b, [int offset = 0, int? length]) β†’ Future<void>
Writes b.length bytes from the specified byte array to this output stream.
override
writeByte(int b) β†’ Future<void>
Writes the specified byte to this output stream.
override
writeBytes(Uint8List data) β†’ Future<void>
Writes all bytes from the specified Uint8List to this output stream.
inherited
writeString(String str) β†’ Future<void>
Writes a string to this output stream using UTF-8 encoding.
inherited
writeTo(ByteArrayOutputStream other) β†’ Future<void>
Writes the contents of another ByteArrayOutputStream to this stream.

Operators

operator ==(Object other) β†’ bool
The equality operator.
inherited