write method

  1. @override
Future<void> write(
  1. List<int> b, [
  2. int offset = 0,
  3. int? length
])
override

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 write
  • offset: 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 {
  await _ensureOpen();

  length ??= b.length - offset;

  if (offset < 0 || length < 0 || offset + length > b.length) {
    throw InvalidArgumentException('Invalid offset or length');
  }

  if (length == 0) {
    return;
  }

  try {
    final bytes = Uint8List.fromList(b.sublist(offset, offset + length));
    await _randomAccessFile!.writeFrom(bytes);
    _position += length;
  } catch (e) {
    throw IOException('Error writing to file: ${_file.path}', cause: e);
  }
}