write method
Writes b.length
bytes from the specified byte array to this output stream.
The general contract for write is that it should have exactly the same
effect as the call write(b, 0, b.length)
.
Parameters
b
: The data to writeoffset
: The start offset in the data (default: 0)length
: The number of bytes to write (default: remaining bytes from offset)
Example
final output = FileOutputStream('output.txt');
try {
// Write entire array
await output.write([72, 101, 108, 108, 111]); // "Hello"
// Write part of array
final data = [32, 87, 111, 114, 108, 100, 33]; // " World!"
await output.write(data, 1, 5); // Write "World"
await output.flush();
} finally {
await output.close();
}
Throws InvalidArgumentException if offset
or length
is negative, or if
offset
+ length
is greater than the length of b
.
Throws IOException if an I/O error occurs.
Throws StreamClosedException if the stream has been closed.
Implementation
@override
Future<void> write(List<int> b, [int offset = 0, int? length]) async {
checkClosed();
length ??= b.length - offset;
if (offset < 0 || length < 0 || offset + length > b.length) {
throw InvalidArgumentException('Invalid offset or length');
}
if (length == 0) {
return;
}
// If the data is larger than our buffer, flush current buffer and write directly
if (length >= _buffer.length) {
await _flushBuffer();
await _output.write(b, offset, length);
return;
}
// If the data won't fit in the current buffer, flush it first
if (_count + length > _buffer.length) {
await _flushBuffer();
}
// Copy data to buffer
_buffer.setRange(_count, _count + length, b, offset);
_count += length;
}