write method

Future<void> write(
  1. String str, [
  2. int offset = 0,
  3. int? length
])

Writes a string.

Parameters

  • str: String to write
  • offset: Offset from which to start writing characters (default: 0)
  • length: Number of characters to write (default: remaining characters from offset)

Example

final writer = FileWriter('output.txt');
try {
  // Write entire string
  await writer.write('Hello, World!');
  
  // Write part of string
  await writer.write('Hello, World!', 7, 5); // Write "World"
  
  await writer.flush();
} finally {
  await writer.close();
}

Throws InvalidArgumentException if offset or length is negative, or if offset + length is greater than the length of str. Throws IOException if an I/O error occurs. Throws StreamClosedException if the writer has been closed.

Implementation

Future<void> write(String str, [int offset = 0, int? length]) async {
  checkClosed();

  length ??= str.length - offset;

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

  final substring = str.substring(offset, offset + length);
  await writeChars(substring.codeUnits);
}