How to work with files and paths in Dart

Read, write, and manipulate files using the dart:io library

Import

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

Add the path package:

dart pub add path

Read a file

// Read entire file as string
var contents = await File('data.txt').readAsString();
var bytes = await File('data.bin').readAsBytes();
var lines = await File('data.txt').readAsLines();

Write a file

// Write string
await File('output.txt').writeAsString('Hello, Dart!');

// Write with mode (append)
await File('log.txt').writeAsString('\nNew entry', mode: FileMode.append);

// Write bytes
await File('data.bin').writeAsBytes([0x01, 0x02, 0x03]);

Check if a file exists

var exists = await File('data.txt').exists();

Delete a file

await File('data.txt').delete();
// Delete if exists
await File('data.txt').delete().catchError((_) => null);

Work with directories

// Create directory
await Directory('output').create(recursive: true);

// List directory contents
var dir = Directory('src');
await for (var entity in dir.list(recursive: true)) {
  if (entity is File) {
    print('File: ${entity.path}');
  } else if (entity is Directory) {
    print('Dir: ${entity.path}');
  }
}

// Check if directory exists
var exists = await Directory('output').exists();

// Delete directory
await Directory('output').delete(recursive: true);

Path manipulation

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

p.basename('/path/to/file.txt');           // 'file.txt'
p.basenameWithoutExtension('/path/to/file.txt'); // 'file'
p.extension('/path/to/file.txt');           // '.txt'
p.dirname('/path/to/file.txt');             // '/path/to'
p.join('path', 'to', 'file.txt');          // 'path/to/file.txt' (platform-aware)
p.normalize('path/./to/../from');           // 'path/from'
p.absolute('file.txt');                      // '/full/path/to/file.txt'
p.relative('/a/b/c', from: '/a');           // 'b/c'