Writing Files in Dart

Here’s the translation of the Go code to Dart, with explanations in Markdown format suitable for Hugo:

Writing files in Dart follows similar patterns to the ones we saw earlier for reading.

import 'dart:io';
import 'dart:convert';

void check(Object? e) {
  if (e != null) {
    throw e;
  }
}

void main() async {
  // To start, here's how to dump a string (or just bytes) into a file.
  var d1 = utf8.encode('hello\ndart\n');
  await File('/tmp/dat1').writeAsBytes(d1);

  // For more granular writes, open a file for writing.
  var f = await File('/tmp/dat2').open(mode: FileMode.write);

  // It's idiomatic to use a try-finally block to ensure
  // the file is closed after we're done with it.
  try {
    // You can write byte lists as you'd expect.
    var d2 = [115, 111, 109, 101, 10];
    var n2 = await f.writeFrom(d2);
    print('wrote $n2 bytes');

    // A writeString method is also available.
    var n3 = await f.writeString('writes\n');
    print('wrote $n3 bytes');

    // Flush writes to stable storage.
    await f.flush();

    // IOSink provides buffered writers in addition
    // to the buffered readers we saw earlier.
    var sink = f.openWrite();
    var n4 = await sink.writeCharCode('b'.codeUnitAt(0));
    n4 += await sink.writeString('uffered\n');
    print('wrote $n4 bytes');

    // Use close to ensure all buffered operations have
    // been applied to the underlying writer.
    await sink.close();
  } finally {
    await f.close();
  }
}

Try running the file-writing code.

$ dart writing_files.dart
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
dart
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.