Async and Practical
Temp File Round Trip
Dart can reserve a fresh temporary directory for short-lived files. This program writes a small text file, reads it back, summarizes the result, and uses a finally block to delete the directory even if the body throws.
Program
Play the program to round-trip two lines of text through a temp file.
file_temp_roundtrip.dart
import 'dart:io';
void main() {
var tempRoot = Directory.systemTemp;
var dir = tempRoot.createTempSync('egtry_dart_');
try {
var path = '${dir.path}/note.txt';
var file = File(path);
var payload = 'Ada\nLin\n';
file.writeAsStringSync(payload);
var text = file.readAsStringSync();
var lines = text.trim().split('\n');
var count = lines.length;
var first = lines[0];
print('lines=$count first=$first');
} finally {
dir.deleteSync(recursive: true);
}
}
Directory.systemTemp
`createTempSync('prefix')` returns a fresh unique temp directory the program can write inside.
write/read round trip
`writeAsStringSync` saves the text, `readAsStringSync` returns the same bytes back as a `String`.
finally cleanup
`finally { dir.deleteSync(recursive: true); }` removes the directory even if the body throws.