Summary - File I/O
- Dart course
- Intermediate
- Lesson 93/116
- 5 min
Combine readAsString, writeAsString and exists to write a notes app.
Summary: File I/O
In this group you saw the dart:io library, reading with readAsStringSync, writing with writeAsStringSync, existence checks with existsSync and folder operations with Directory. File operations give persistent data.
Now we combine them: we will write and read a notebook. This is a small persistent storage example.
Remember: writing overwrites by default; append adds to the end; an existence check prevents errors.
Practice The notebook
Import the library with import 'dart:io';. In main create File('book.txt'). Write two lines with writeAsStringSync('line1\nline2'). Then read with readAsStringSync() and print it with print.
Starter code
// Import the dart:io library
void main() {
// write two lines to book.txt, read and print
}Sample solution
import 'dart:io';
void main() {
var f = File('book.txt');
f.writeAsStringSync('line1\nline2');
print(f.readAsStringSync());
}Expected output
line1 line2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Concept matching
| Term | Meaning |
|---|---|
readAsStringSync() |
Reading |
writeAsStringSync() |
Writing |
existsSync() |
Existence |
Directory |
Folder |
2 What does writeAsStringSync do without a mode?
- Deletes the file
- Appends
- Throws
- Overwrites Correct answer
Explanation: without a mode it overwrites.
3 The readAsStringSync call
var content = f.____();
var content = f.readAsStringSync();
Explanation: the file is read with readAsStringSync().