Files and directories

suggest change

File system access in Dart lives in dart:io. It's available in command-line programs, servers and Flutter apps on desktop and mobile, but not on the web.

There are three classes, all subclasses of FileSystemEntity:

Creating a File or Directory object doesn't touch the disk. It's only a path. The disk is accessed when you call a method such as readAsString, create or list.

Almost every method comes in two versions: an asynchronous one returning a Future or Stream (readAsString, exists, list) and a synchronous one with a Sync suffix (readAsStringSync, existsSync, listSync). Use the async versions in servers and Flutter apps, so a slow disk doesn't block the event loop. The sync versions are fine in scripts and command-line tools.

This article covers:

The examples were run with Dart 3.13 on Windows, which is why paths are printed with \. On Linux and macOS you get /.

Reading and writing a whole file

For files that fit comfortably in memory, use the one-call methods:

import 'dart:io';

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

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

  final text = await file.readAsString();
  print(text);

  final lines = await file.readAsLines();
  print(lines);

  final bytes = await file.readAsBytes();
  print('${bytes.length} bytes, first: ${bytes.take(5).toList()}');

  print(file.path);
  print(file.absolute.path);
}

Output:

first line
second line
third line

[first line, second line, third line]
34 bytes, first: [102, 105, 114, 115, 116]
notes.txt
C:\Users\kjk\AppData\Local\Temp\pbw-fs45\demo2\notes.txt

writeAsString also takes flush: true, which waits until the OS has written the data to disk before the Future completes. Writing a file in place is not atomic: a crash halfway leaves a truncated file. For files that must never be seen half-written, write to a temporary file and rename it, as shown in Temporary files.

Other encodings

Pass encoding: to read or write in another encoding. dart:convert has utf8, latin1, ascii and systemEncoding:

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

Future<void> main() async {
  final file = File('legacy.txt');
  await file.writeAsString('Café Zürich', encoding: latin1);
  print(await file.length()); // 1 byte per character

  print(await file.readAsString(encoding: latin1));

  // utf8.decode with allowMalformed replaces bad bytes instead of throwing.
  final bytes = await file.readAsBytes();
  print(utf8.decode(bytes, allowMalformed: true));
}

Output:

11
Café Zürich
Caf� Z�rich

Reading a file that isn't valid UTF-8 with readAsString throws a FileSystemException. When you'd rather get replacement characters, read bytes and decode them with allowMalformed: true. More in Unicode and encodings.

Streaming large files

readAsString loads the whole file into memory. For a multi-gigabyte log, read it as a stream of bytes with openRead, decode it, and split it into lines. For writing many small pieces, use openWrite, which returns an IOSink that buffers writes:

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

Future<void> main() async {
  // Create a larger log file with an IOSink.
  final log = File('app.log');
  final sink = log.openWrite();
  for (var i = 1; i <= 100000; i++) {
    final level = i % 1000 == 0 ? 'ERROR' : 'INFO';
    sink.writeln('$level request $i handled');
  }
  await sink.close(); // flushes and closes the file
  print('size: ${await log.length()} bytes');

  // Read it back line by line without loading it into memory.
  var total = 0;
  var errors = 0;
  final lines = log
      .openRead()
      .transform(utf8.decoder)
      .transform(const LineSplitter());
  await for (final line in lines) {
    total++;
    if (line.startsWith('ERROR')) errors++;
  }
  print('lines: $total, errors: $errors');
}

Output:

size: 2688995 bytes
lines: 100000, errors: 100

Things to know about IOSink:

openRead(start, end) reads only a byte range of the file.

Random access

To read or write at a specific position, open the file and get a RandomAccessFile. This is how you'd work with fixed-size records, file headers or a simple binary format:

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

const recordSize = 8;

Future<void> main() async {
  final file = File('records.bin');
  // 5 fixed-size records: "rec0000\n", "rec0001\n", ...
  await file.writeAsString([
    for (var i = 0; i < 5; i++) 'rec${i.toString().padLeft(4, '0')}\n',
  ].join());

  // FileMode.append opens for reading and writing without truncating;
  // the position starts at the end but can be moved.
  final raf = await file.open(mode: FileMode.append);
  try {
    print('length:   ${await raf.length()}');
    print('position: ${await raf.position()}');

    // Read record 3 without touching the rest of the file.
    await raf.setPosition(3 * recordSize);
    print('record 3: ${ascii.decode(await raf.read(recordSize - 1))}');

    // Overwrite record 1 in place.
    await raf.setPosition(1 * recordSize);
    await raf.writeString('REC0001');

    // Cut the file down to 4 records.
    await raf.truncate(4 * recordSize);
  } finally {
    await raf.close();
  }

  print(await file.readAsLines());
}

Output:

length:   40
position: 40
record 3: rec0003
[rec0000, REC0001, rec0002, rec0003]

Pick the mode carefully:

Mode Read Write Creates file Truncates Starts at
FileMode.read yes no no no start
FileMode.write yes yes yes yes start
FileMode.append yes yes yes no end
FileMode.writeOnly no yes yes yes start
FileMode.writeOnlyAppend no yes yes no end

To modify an existing file in place, use FileMode.append and setPosition. FileMode.write erases the file first.

A RandomAccessFile allows only one pending operation at a time, so await each call before starting the next one, and close it in finally. It also has lock and unlock for advisory file locks between processes.

Does it exist, and what is it?

import 'dart:io';

Future<void> main() async {
  await File('data.txt').writeAsString('hello');
  await Directory('out').create();

  for (final path in ['data.txt', 'out', 'missing.txt']) {
    final type = await FileSystemEntity.type(path);
    print('$path: $type');
  }

  print(await File('data.txt').exists());
  print(await Directory('data.txt').exists()); // it's a file, not a dir

  final stat = await File('data.txt').stat();
  print('type:     ${stat.type}');
  print('size:     ${stat.size}');
  print('modified: ${stat.modified}');
  print('mode:     ${stat.modeString()}');

  final missing = await File('missing.txt').stat();
  print('missing:  ${missing.type}, size ${missing.size}');
}

Output:

data.txt: file
out: directory
missing.txt: notFound
true
false
type:     file
size:     5
modified: 2026-10-17 22:18:13.045273
mode:     rw-rw-rw-
missing:  notFound, size -1

Don't use exists() to protect against errors: checking first and then opening is a race, because another process can delete or create the file in between. Just try the operation and handle the exception.

Handling errors

Failed file operations throw FileSystemException. It has the operation's message, the path, and the osError with the operating system's error code and text. Common errors have subclasses, so you can catch them specifically:

import 'dart:io';

Future<void> main() async {
  try {
    await File('no/such/file.txt').readAsString();
  } on PathNotFoundException catch (e) {
    print('not found: ${e.path}');
    print('os error:  ${e.osError?.message} (code ${e.osError?.errorCode})');
  }

  await Directory('locked').create();
  try {
    await File('locked').readAsString(); // a directory, not a file
  } on FileSystemException catch (e) {
    print('${e.runtimeType}: ${e.message}, ${e.osError?.message}');
  }

  // Invalid UTF-8 is a different error: it comes from the decoder.
  await File('binary.dat').writeAsBytes([0xff, 0xfe, 0x00]);
  try {
    await File('binary.dat').readAsString();
  } on FileSystemException catch (e) {
    print('decode: ${e.message}');
  }
}

Output:

not found: no/such/file.txt
os error:  The system cannot find the path specified (code 3)
PathAccessException: Cannot open file, Access is denied
decode: Failed to decode data using encoding 'utf-8'

Opening a directory as a file reports "Access is denied" on Windows. On Linux the OS error is "Is a directory". The error text and codes come from the OS, so don't parse them. Catch the subclass, or use osError.errorCode together with a check of Platform.isWindows.

Building paths with package:path

Concatenating paths with '$dir/$name' mostly works, because Windows also accepts /. But it breaks when dir ends with a separator, and you get mixed separators in paths shown to users. The path package from the Dart team does it properly:

dart pub add path
import 'dart:io';

import 'package:path/path.dart' as p;

void main() {
  final path = p.join('photos', '2026', 'beach.jpeg');
  print(path);
  print(p.basename(path));
  print(p.basenameWithoutExtension(path));
  print(p.extension(path));
  print(p.dirname(path));
  print(p.split(path));
  print(p.setExtension(path, '.webp'));
  print(p.normalize('photos/./2026/../2025/x.jpg'));
  print(p.isAbsolute(path));
  print(p.relative(p.join('a', 'b', 'c.txt'), from: 'a'));

  // Explicit styles work the same on every OS.
  print(p.posix.join('usr', 'local', 'bin'));
  print(p.windows.join(r'C:\', 'Users', 'me'));
  print(p.url.join('https://example.com', 'docs', 'index.html'));

  print(Platform.pathSeparator);
}

Output:

photos\2026\beach.jpeg
beach.jpeg
beach
.jpeg
photos\2026
[photos, 2026, beach.jpeg]
photos\2026\beach.webp
photos\2025\x.jpg
false
b\c.txt
usr/local/bin
C:\Users\me
https://example.com/docs/index.html
\

Platform.pathSeparator is the separator as a string if you don't want the package.

Working directory and script location

Relative paths are resolved against Directory.current, which is wherever the program was started from, not where the script is. To find files shipped next to a script, use Platform.script:

import 'dart:io';

import 'package:path/path.dart' as p;

void main() {
  print('cwd:    ${p.basename(Directory.current.path)}');
  print('script: ${p.basename(Platform.script.toFilePath())}');

  // Resolve data files next to the script, not the working directory.
  final scriptDir = p.dirname(Platform.script.toFilePath());
  final config = File(p.join(scriptDir, 'config.json'));
  print('config: ${p.relative(config.path, from: p.dirname(scriptDir))}');

  Directory.current = scriptDir; // change the working directory
  print('cwd:    ${p.basename(Directory.current.path)}');
}

Running dart run tool/where.dart from the project directory prints:

cwd:    fsart
script: where.dart
config: tool\config.json
cwd:    tool

Directory.current is a setter as well, but it changes the working directory of the whole process, including all isolates. Prefer building absolute paths. In a program compiled with dart compile exe, use Platform.resolvedExecutable instead of Platform.script to find the executable's directory.

Creating and listing directories

create(recursive: true) works like mkdir -p: it creates missing parent directories and doesn't fail if the directory already exists. list() returns a Stream of FileSystemEntity objects:

import 'dart:io';

import 'package:path/path.dart' as p;

Future<void> main() async {
  // create(recursive: true) creates missing parents, like mkdir -p,
  // and doesn't fail if the directory already exists.
  final root = Directory('project');
  await Directory(p.join('project', 'lib', 'src')).create(recursive: true);
  await Directory(p.join('project', 'test')).create(recursive: true);
  await Directory(p.join('project', 'lib', 'src')).create(recursive: true);

  await File(p.join('project', 'README.md')).writeAsString('# Project');
  await File(p.join('project', 'lib', 'main.dart')).writeAsString('void main() {}');
  await File(p.join('project', 'lib', 'src', 'util.dart')).writeAsString('// util');
  await File(p.join('project', 'test', 'main_test.dart')).writeAsString('// test');

  print('-- direct children:');
  await for (final entity in root.list()) {
    final kind = entity is Directory ? 'dir ' : 'file';
    print('$kind ${p.basename(entity.path)}');
  }

  print('-- all .dart files:');
  final dartFiles = await root
      .list(recursive: true)
      .where((e) => e is File && p.extension(e.path) == '.dart')
      .map((e) => p.relative(e.path, from: root.path))
      .toList();
  dartFiles.sort();
  dartFiles.forEach(print);
}

Output:

-- direct children:
dir  lib
file README.md
dir  test
-- all .dart files:
lib\main.dart
lib\src\util.dart
test\main_test.dart

listSync() returns a List directly, which is simpler in a script.

dart:io has no glob matching. Filter with p.extension, a RegExp, or use package:glob.

Walking a tree: disk usage

Here is a small du: the total size of all files in a directory tree and the largest files. It also shows the sync methods:

import 'dart:io';

import 'package:path/path.dart' as p;

/// Total size of all files under [dir], and the largest ones.
Future<void> report(Directory dir) async {
  var total = 0;
  var count = 0;
  final sizes = <String, int>{};
  await for (final entity in dir.list(recursive: true, followLinks: false)) {
    if (entity is! File) continue;
    final size = (await entity.stat()).size;
    total += size;
    count++;
    sizes[p.relative(entity.path, from: dir.path)] = size;
  }
  print('$count files, $total bytes');
  final largest = sizes.entries.toList()
    ..sort((a, b) => b.value.compareTo(a.value));
  for (final e in largest.take(3)) {
    print('${e.value.toString().padLeft(8)}  ${e.key}');
  }
}

Future<void> main() async {
  // Sync versions of every method exist: handy in scripts and CLI tools.
  for (final name in ['a', 'b/c', 'b/d']) {
    Directory(name).createSync(recursive: true);
  }
  File('a/small.txt').writeAsStringSync('x' * 10);
  File('b/c/big.bin').writeAsBytesSync(List.filled(50000, 0));
  File('b/d/medium.log').writeAsStringSync('log line\n' * 1000);
  File('b/d/tiny').writeAsStringSync('');

  await report(Directory('.'));
}

Output:

4 files, 59010 bytes
   50000  b\c\big.bin
    9000  b\d\medium.log
      10  a\small.txt

For a tree with many files, stat() per file is the slow part. list doesn't return file sizes, so there's no way around one stat per file.

Copying, moving and deleting

import 'dart:io';

Future<void> main() async {
  final original = File('report.txt');
  await original.writeAsString('Q3 numbers');

  // copy returns the new File; the original stays.
  final backup = await original.copy('report.bak');
  print('copied:  ${backup.path}, ${await backup.readAsString()}');

  // rename moves the file and returns a File for the new path.
  // The old File object still points at the old (now missing) path.
  await Directory('archive').create();
  final moved = await original.rename('archive/report-q3.txt');
  print('moved:   ${moved.path}');
  print('old exists: ${await original.exists()}');

  // delete fails if the file doesn't exist...
  await backup.delete();
  try {
    await backup.delete();
  } on PathNotFoundException {
    print('already deleted');
  }

  // ...so check first when "maybe missing" is fine.
  if (await backup.exists()) await backup.delete();

  // A non-empty directory needs recursive: true.
  try {
    await Directory('archive').delete();
  } on FileSystemException catch (e) {
    print('delete dir: ${e.osError?.message}');
  }
  await Directory('archive').delete(recursive: true);
  print('archive exists: ${await Directory('archive').exists()}');
}

Output:

copied:  report.bak, Q3 numbers
moved:   archive/report-q3.txt
old exists: false
already deleted
delete dir: The directory is not empty
archive exists: false

Copying a directory and moving across drives

There's no built-in method to copy a directory, and rename can't move files between file systems (different drives on Windows, different mounts on Linux). Both are short to write:

import 'dart:io';

import 'package:path/path.dart' as p;

/// Copies the contents of [source] into [destination], creating it.
Future<void> copyDirectory(Directory source, Directory destination) async {
  await destination.create(recursive: true);
  await for (final entity in source.list(followLinks: false)) {
    final target = p.join(destination.path, p.basename(entity.path));
    if (entity is Directory) {
      await copyDirectory(entity, Directory(target));
    } else if (entity is File) {
      await entity.copy(target);
    } else if (entity is Link) {
      await Link(target).create(await entity.target());
    }
  }
}

/// Moves [file] to [newPath], falling back to copy + delete when
/// rename can't move between file systems (drives, mounts).
Future<File> moveFile(File file, String newPath) async {
  try {
    return await file.rename(newPath);
  } on FileSystemException {
    final copy = await file.copy(newPath);
    await file.delete();
    return copy;
  }
}

Future<void> main() async {
  await Directory('site/css').create(recursive: true);
  await File('site/index.html').writeAsString('<h1>Hi</h1>');
  await File('site/css/style.css').writeAsString('h1 { color: red }');

  await copyDirectory(Directory('site'), Directory('site-backup'));

  await for (final e in Directory('site-backup').list(recursive: true)) {
    print(p.relative(e.path, from: 'site-backup'));
  }

  final moved = await moveFile(File('site-backup/index.html'), 'index.old.html');
  print('moved to ${moved.path}');
}

Output:

css
css\style.css
index.html
moved to index.old.html

moveFile falls back to copy and delete on any FileSystemException. That also covers errors that copying can't fix, such as a missing source, but then copy fails with the same error, which is what you want to see.

Copying symlinks requires permission on Windows (Developer Mode or administrator), so Link.create can fail there. To bundle a directory into a single file, see ZIP archives, which also shows how to zip a folder and extract an archive safely.

Watching for changes

watch() on a directory (or a file) returns a stream of change events. It's what dev servers and build tools use to rebuild when files change:

import 'dart:async';
import 'dart:io';

import 'package:path/path.dart' as p;

Future<void> main() async {
  final dir = await Directory('watched').create();

  final sub = dir.watch().listen((event) {
    final name = p.basename(event.path);
    final kind = switch (event) {
      FileSystemCreateEvent() => 'created',
      FileSystemModifyEvent() => 'modified',
      FileSystemDeleteEvent() => 'deleted',
      FileSystemMoveEvent(:final destination) =>
        'moved to ${p.basename(destination ?? '?')}',
      _ => 'other',
    };
    print('$kind: $name');
  });

  // Give the watcher a moment to start, then make some changes.
  await Future<void>.delayed(const Duration(milliseconds: 200));
  final f = File(p.join(dir.path, 'config.json'));
  await f.writeAsString('{}');
  await Future<void>.delayed(const Duration(milliseconds: 200));
  await f.rename(p.join(dir.path, 'config.old'));
  await Future<void>.delayed(const Duration(milliseconds: 200));
  await File(p.join(dir.path, 'config.old')).delete();

  await Future<void>.delayed(const Duration(milliseconds: 500));
  await sub.cancel();
}

Output:

created: config.json
modified: config.json
moved to config.old: config.json
deleted: config.old

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents