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
Replay: real traced execution (multi-file project)
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);
}
}
tempRoot ← system temp
3void main() {4 var tempRoot = Directory.systemTemp;5 var dir = tempRoot.createTempSync('egtry_dart_');values this stepsystem temptempRootdir ← temp directory
4var tempRoot = Directory.systemTemp;5var dir = tempRoot.createTempSync('egtry_dart_');6try {values this steptemp directorydirpath ← <temp>/note.txt
6try {7 var path = '${dir.path}/note.txt';8 var file = File(path);values this step<temp>/note.txtpathfile ← File handle
7var path = '${dir.path}/note.txt';8var file = File(path);9var payload = 'Ada\nLin\n';values this stepFile handlefile<temp>/note.txtpathpayload ← Ada\nLin\n
8var file = File(path);9var payload = 'Ada\nLin\n';10file.writeAsStringSync(payload);values this stepAda\nLin\npayloadcontent ← written
9var payload = 'Ada\nLin\n';10file.writeAsStringSync(payload);11var text = file.readAsStringSync();values this stepwrittencontentAda\nLin\npayloadtext ← Ada\nLin\n
10file.writeAsStringSync(payload);11var text = file.readAsStringSync();12var lines = text.trim().split('\n');values this stepAda\nLin\ntextwrittencontentlines ← [Ada, Lin]
11var text = file.readAsStringSync();12var lines = text.trim().split('\n');13var count = lines.length;values this step[Ada, Lin]linesAda\nLin\ntextcount ← 2
12var lines = text.trim().split('\n');13var count = lines.length;14var first = lines[0];values this step2count[Ada, Lin]linesfirst ← Ada
13var count = lines.length;14var first = lines[0];15print('lines=$count first=$first');values this stepAdafirstAdalines[0]print('lines=$count first=$first');
14 var first = lines[0];15 print('lines=$count first=$first');16} finally {outputlines=2 first=Adavalues this step2countAdafirstdir ← removed
16} finally {17 dir.deleteSync(recursive: true);18}values this stepremoveddir
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.