Temporary Files And Directories in Dart

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

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

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

void main() async {
  // The easiest way to create a temporary file in Dart is by
  // using the `File.createTemp` method. It creates a file and
  // opens it for reading and writing. We provide an empty string
  // as the first argument, so it will create the file in the
  // default temporary directory for our OS.
  var file = await File.createTemp('sample');
  check(file == null);

  // Display the name of the temporary file. On
  // Unix-based OSes the directory will likely be `/tmp`.
  // The file name starts with the prefix given as the
  // argument to `File.createTemp` and the rest
  // is chosen automatically to ensure that concurrent
  // calls will always create different file names.
  print('Temp file name: ${file.path}');

  // Clean up the file after we're done. The OS is
  // likely to clean up temporary files by itself after
  // some time, but it's good practice to do this
  // explicitly.
  await file.delete();

  // We can write some data to the file.
  await file.writeAsBytes([1, 2, 3, 4]);

  // If we intend to create many temporary files, we may
  // prefer to create a temporary *directory*.
  // `Directory.systemTemp` provides the system temp directory,
  // and we can create a new directory inside it.
  var tempDir = await Directory.systemTemp.createTemp('sampledir');
  print('Temp dir name: ${tempDir.path}');

  // Clean up the directory after we're done.
  await tempDir.delete(recursive: true);

  // Now we can synthesize temporary file names by
  // prefixing them with our temporary directory.
  var tempFilePath = path.join(tempDir.path, 'file1');
  await File(tempFilePath).writeAsBytes([1, 2]);
}

To run the program, save it as temporary_files_and_directories.dart and use dart run:

$ dart run temporary_files_and_directories.dart
Temp file name: /tmp/sample12345678
Temp dir name: /tmp/sampledir87654321

In this Dart version:

  1. We use the dart:io library for file and directory operations.
  2. The path package is used for path manipulation.
  3. Instead of os.CreateTemp, we use File.createTemp.
  4. For directory creation, we use Directory.systemTemp.createTemp.
  5. File operations are asynchronous in Dart, so we use async/await.
  6. Error handling is simplified with the check function.
  7. File deletion is done with the delete method.
  8. We use writeAsBytes to write data to files.

The core concepts remain the same, but the implementation is adapted to Dart’s idioms and asynchronous nature.