Dart Files
Dart Files
Programs often need to save data in a file, so the data is still there the next time the program runs.
In Dart, you work with files through the File class from the dart:io library.
To use a file, create a File object with the name (or path) of the file:
import 'dart:io';
final file = File('notes.txt');
Creating the File object does not create the file on the disk.
It is only a way to point to the file.
Note: The examples on this page delete the files they create at the end, so they do not leave files behind.
Write and Read a File
The writeAsStringSync() method writes a string to the file.
If the file does not exist, it is created.
If the file already exists, the old content is replaced.
The readAsStringSync() method reads the whole file and returns it as a string:
Example
import 'dart:io';
void main() {
final file = File('greeting.txt');
file.writeAsStringSync('Hello from a file!');
String content = file.readAsStringSync();
print(content);
file.deleteSync();
}
Try it Yourself »
Result:
Hello from a file!
The word Sync at the end of the name means that the method is synchronous: the program waits until the work is done.
Check if a File Exists
The existsSync() method returns true if the file exists.
The deleteSync() method deletes the file:
Example
import 'dart:io';
void main() {
final file = File('scores.txt');
print(file.existsSync());
file.writeAsStringSync('100');
print(file.existsSync());
file.deleteSync();
print(file.existsSync());
}
Try it Yourself »
Result:
false
true
false
It is a good idea to check that a file exists before you read it.
Add to a File and Read Lines
To add text at the end of a file, instead of replacing it, use mode: FileMode.append.
The readAsLinesSync() method reads the file and returns a list with one string for each line:
Example
import 'dart:io';
void main() {
final file = File('shopping.txt');
file.writeAsStringSync('Milk\n');
file.writeAsStringSync('Bread\n', mode: FileMode.append);
file.writeAsStringSync('Eggs\n', mode: FileMode.append);
List<String> items = file.readAsLinesSync();
print(items);
for (String item in items) {
print('Buy $item');
}
file.deleteSync();
}
Try it Yourself »
Result:
[Milk, Bread, Eggs]
Buy Milk
Buy Bread
Buy Eggs
The \n at the end of each string is a new line.
Async File Methods
Reading and writing a big file can take time.
Each method also has an async version without Sync in its name, which returns a future.
Use them with await, so the rest of the program does not have to stop and wait:
| Sync method | Async method |
|---|---|
writeAsStringSync() | writeAsString() |
readAsStringSync() | readAsString() |
readAsLinesSync() | readAsLines() |
existsSync() | exists() |
deleteSync() | delete() |
Example
import 'dart:io';
Future<void> main() async {
final file = File('diary.txt');
await file.writeAsString('Today I learned about files.');
bool found = await file.exists();
print('File exists: $found');
String text = await file.readAsString();
print(text);
await file.delete();
print('File exists: ${await file.exists()}');
}
Try it Yourself »
Result:
File exists: true
Today I learned about files.
File exists: false
Handle Errors
If you try to read a file that does not exist, Dart throws a FileSystemException.
Use try and catch to handle it:
Example
import 'dart:io';
void main() {
final file = File('missing.txt');
try {
String content = file.readAsStringSync();
print(content);
} on FileSystemException {
print('Could not read the file');
}
}
Try it Yourself »
Result:
Could not read the file
Note: Like all of dart:io, the File class does not work in Dart programs that run in a web browser.