DartIntermediate 2 min read

Dart file I/O: write and read a small export safely

Use asynchronous local file APIs and release only the temporary directory owned by the operation.

On this page

A command-line export needs a real file system, which the browser editor does not provide. This complete local example creates its own temporary directory, writes UTF-8 data, reads it back and cleans up only that owned directory.

Worked example

Language requirement: Dart 3.0 or later. Use a local Dart project; read the file/dependency instructions before running this example.

import 'dart:io';

Future<void> main() async {
  final directory = await Directory.systemTemp.createTemp('fever-export-');
  final file = File('${directory.path}/invoice.csv');
  try {
    await file.writeAsString('id,totalPaise\nINV-7,25000\n', flush: true);
    final text = await file.readAsString();
    print(text.trim());
  } finally {
    await directory.delete(recursive: true);
  }
}

Follow the data and control flow

Each asynchronous operation is awaited, so reading begins after writing completes. The finally block runs after success or failure and removes the directory created by this invocation. It never accepts a user-provided deletion target.

For a large file, prefer streaming reads such as openRead with a UTF-8 decoder and line splitter instead of loading the entire file into memory. A write stream must be flushed and closed. An application export should use a deliberate destination and overwrite policy rather than a temporary scratch directory.

A mistake to avoid

Do not compose a file path directly from an untrusted upload name or recursively delete a computed user path as cleanup. Validate and resolve paths within the intended root. Concurrent writers can also overwrite one another; durable storage and atomic-update policies require a separate design.

Practice and verification

Introduce a read failure and verify finally still executes. Rewrite the read as a stream of lines for a larger generated file. Explain which data should survive after the command ends and which is safe to treat as temporary.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.