Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 61 ยท Errors and Libraries

Files, Directories and Command-Line Programs

Read and write files, list directories, take command-line arguments, read stdin, set exit codes and run other programs with Dart's dart:io library.

Dart is not only for apps with screens. With the dart:io library you can read and write files, walk folders, talk to the terminal and start other programs, which is everything a command-line tool needs. The library works on the Dart VM and in compiled executables, on Windows, macOS and Linux. It does not exist in browsers, so Flutter web and other JavaScript builds cannot import it.

The Dart code in this lesson is read-only, because the site cannot run dart:io. The TypeScript stand-ins use Node.js, whose fs, process and child_process modules have the same shape, so you can run each idea.

Reading and writing files

File represents a path, whether or not the file exists yet. Most methods come in two flavours: an async one that returns a Future, and a Sync one that blocks until it is done.

DART
import 'dart:io';

Future<void> main() async {
  var file = File('notes.txt');

  await file.writeAsString('first line\nsecond line\n');
  await file.writeAsString('third line\n', mode: FileMode.append);

  String all = await file.readAsString();
  List<String> lines = await file.readAsLines();
  print(lines.length);                 // 3
  print(lines.last);                   // third line

  print(await file.exists());          // true
  print(await file.length());          // size in bytes

  await file.delete();
}

writeAsString replaces the file unless you pass mode: FileMode.append. For bytes use readAsBytes and writeAsBytes. Prefer the async versions in programs that do other work at the same time (such as servers). In a small script, readAsStringSync() is shorter and perfectly fine, and it avoids async entirely. If you need a refresher on await, see Futures and async/await.

Files that are too big for memory should be streamed. openRead() gives a Stream<List<int>> that you decode and split into lines:

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

Future<void> main() async {
  var lines = File('server.log')
      .openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());

  var errors = 0;
  await for (final line in lines) {
    if (line.contains('ERROR')) {
      errors++;
    }
  }
  print('errors: $errors');
}

For writing in pieces, file.openWrite() returns an IOSink: call write or writeln as often as you like, then await sink.close(). Forgetting close can lose buffered data.

Errors from the file system

Things go wrong: the file is missing, the disk is full, you lack permission. dart:io throws a FileSystemException (a missing file is the subtype PathNotFoundException). Catch it where you can do something useful:

DART
import 'dart:io';

Future<String> loadConfig(String path) async {
  try {
    return await File(path).readAsString();
  } on FileSystemException catch (e) {
    stderr.writeln('Cannot read $path: ${e.message}');
    return '{}';                       // fall back to an empty config
  }
}

The exception carries message, path and an osError with the operating system's code. See Exceptions and Error Handling for try, on and catch in detail. A good habit is to check the file exists only when "missing" is a normal case; otherwise just try the read and handle the failure, because the file can disappear between the check and the read.

TypeScript Write, append, read and delete a file (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Directories

Directory creates, lists and deletes folders:

DART
import 'dart:io';

Future<void> main() async {
  var project = Directory('out/reports');
  await project.create(recursive: true);        // creates out and out/reports

  await File('out/reports/a.txt').writeAsString('A');
  await File('out/reports/b.csv').writeAsString('B');

  await for (final entity in Directory('out').list(recursive: true)) {
    if (entity is File) {
      print('file: ${entity.path}');
    } else if (entity is Directory) {
      print('dir:  ${entity.path}');
    }
  }

  var temp = await Directory.systemTemp.createTemp('demo_');
  print(temp.path);                             // a fresh folder in the OS temp area

  await Directory('out').delete(recursive: true);
}

list returns a Stream<FileSystemEntity>; each item is a File, a Directory or a Link, so test it with is. Use listSync() for a simple list. Paths are plain strings, and the separator differs between Windows and other systems (Platform.pathSeparator). Do not glue paths with '$dir/$name' in code that must be portable; the package:path package offers p.join('out', 'reports', 'a.txt') and helpers like p.basename and p.extension.

Command-line programs

A command-line program has a main that receives the arguments as a list of strings. Run it with dart run bin/greet.dart Ada --shout:

DART
import 'dart:io';

void main(List<String> args) {
  if (args.isEmpty) {
    stderr.writeln('Usage: greet <name> [--shout]');
    exit(64);                               // 64 is the "usage error" convention
  }

  var shout = args.contains('--shout');
  var name = args.firstWhere((a) => !a.startsWith('--'));
  var message = 'Hello, $name!';
  stdout.writeln(shout ? message.toUpperCase() : message);
}

stdout and stderr are streams of text with write, writeln and flush. Send normal results to stdout and errors or diagnostics to stderr, so that users can pipe the output of your program into another tool without mixing in error messages.

For real option parsing (flags, named options, --help text), use package:args and its ArgParser, rather than writing your own loops over args.

Reading from the keyboard

stdin.readLineSync() waits for a line and returns String?: it is null when the input ends (for example when the user presses Ctrl+D, or when a file is piped in and runs out):

DART
import 'dart:io';

void main() {
  stdout.write('Your name: ');
  String? name = stdin.readLineSync();
  if (name == null || name.trim().isEmpty) {
    stderr.writeln('No name given.');
    exitCode = 1;
    return;
  }
  print('Nice to meet you, ${name.trim()}.');
}

To read all of standard input as a stream, use stdin.transform(utf8.decoder).transform(const LineSplitter()) and await for. Because input may come from a pipe or a file, never assume a person is typing.

Exit codes

Every process ends with an integer exit code. By convention 0 means success and anything else means failure; shell scripts and CI systems read it. In Dart you have two choices:

  • exit(2) ends the program immediately.
  • exitCode = 2; sets the code but lets main finish normally, so pending cleanup and finally blocks run.

Prefer the second form. A main that returns normally ends with 0 unless the code was set or an uncaught error occurred (an uncaught exception ends the program with a non-zero code and a stack trace).

flowchart LR
    A["dart run app.dart a b"] --> M["main(args)<br/>args = [a, b]"]
    I["stdin"] --> M
    M --> O["stdout<br/>results"]
    M --> E["stderr<br/>errors"]
    M --> X["exit code<br/>0 = success"]

A command-line program: arguments and stdin go in; stdout, stderr and an exit code come out.

TypeScript Arguments, stdout/stderr and exit codes (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Running other programs

Process.run starts another program, waits for it, and collects its output:

DART
import 'dart:io';

Future<void> main() async {
  ProcessResult result = await Process.run('git', ['--version']);
  print(result.exitCode);        // 0 on success
  print(result.stdout);          // the text the program printed
  print(result.stderr);          // errors, if any
}

Pass the program and its arguments as separate list items instead of building one command string. That avoids quoting problems and shell-injection bugs. Use Process.start when you need to stream the output while the program is still running, or to write to its input. If the program does not exist, a ProcessException is thrown. Finally, Platform.environment is a map of environment variables, and Platform.isWindows, Platform.operatingSystem and Platform.numberOfProcessors describe the machine.

TypeScript Starting a child process (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On which platforms can you import dart:io?

    dart:io needs an operating system. Browsers have no direct file system or process access, so web builds cannot use it.
  2. 2. What does File('log.txt').writeAsString('hi') do if the file already exists?

    The default mode is FileMode.write, which overwrites. Pass mode: FileMode.append to add text to the end.
  3. 3. Why is exitCode = 2; often better than exit(2)?

    exit() stops at once. Setting exitCode records the code and the program ends in the normal way.
  4. 4. What does stdin.readLineSync() return when the input has ended?

    The result type is String?. It is null at end of input (Ctrl+D or an exhausted pipe), so always check for null.
  5. 5. Why pass command arguments to Process.run as a list?

    Each list item is exactly one argument, so spaces and special characters in values cannot change the meaning of the command.

Summary

  • dart:io provides File, Directory, stdin, stdout, stderr, Process and Platform; it is unavailable in web builds.
  • File methods come as async (Future) and Sync versions; stream large files with openRead and LineSplitter.
  • writeAsString overwrites unless you use FileMode.append; close an IOSink when done.
  • Catch FileSystemException where you can react; check types in list() results with is.
  • main(List<String> args) receives arguments; results go to stdout, errors to stderr; stdin.readLineSync() can return null.
  • Exit code 0 means success; prefer exitCode = n over exit(n).
  • Process.run takes the program and a list of arguments.

Next, start working with time-consuming operations in Futures and async/await.