Dart File Operations
In this lesson, you will learn how Dart programs work with files. File operations allow applications to read, write, update, and manage data stored on the local system.
Real-world applications use file handling for logs, reports, configuration files, exports, backups, and data processing.
Why File Operations Matter
Files are essential when applications need to:
- Store data permanently
- Read configuration values
- Generate reports
- Maintain logs
Dart provides file handling support through the dart:io library.
Importing File Support
To work with files, you must import the IO library.
import 'dart:io';
Creating a File
Let’s create a file that stores daily sales data.
void main() {
File file = File('sales.txt');
file.writeAsStringSync('Day 1: \$1200');
print("File created and data written");
}
This creates a file named sales.txt and writes initial data.
Writing Data to a File
Writing data allows applications to store runtime information.
void main() {
File file = File('report.txt');
file.writeAsStringSync('Total Users: 350\nRevenue: \$8200');
print("Report saved");
}
Each execution updates the file content.
Appending Data to a File
Appending is useful for logs where existing data should remain unchanged.
void main() {
File file = File('logs.txt');
file.writeAsStringSync(
'Login successful at 10:45 AM\n',
mode: FileMode.append
);
print("Log updated");
}
Reading Data from a File
Reading files allows applications to process stored data.
void main() {
File file = File('sales.txt');
String content = file.readAsStringSync();
print("File content:");
print(content);
}
This reads the full file as a single string.
Reading File Line by Line
Line-by-line reading is useful for large files.
void main() {
File file = File('logs.txt');
List lines = file.readAsLinesSync();
for (var line in lines) {
print(line);
}
}
Checking if a File Exists
Before reading or writing, it is good practice to check file existence.
void main() {
File file = File('config.txt');
if (file.existsSync()) {
print("Configuration file found");
} else {
print("Configuration file missing");
}
}
Deleting a File
Deleting files helps manage storage and clean unused data.
void main() {
File file = File('old_data.txt');
if (file.existsSync()) {
file.deleteSync();
print("File deleted");
}
}
Error Handling in File Operations
File operations may fail due to permissions or missing files. Always handle errors safely.
void main() {
try {
File file = File('secure.txt');
print(file.readAsStringSync());
} catch (e) {
print("Error reading file: $e");
}
}
Real-World Example: Sales Summary
This example reads daily sales values and calculates the total.
void main() {
File file = File('daily_sales.txt');
List lines = file.readAsLinesSync();
int total = 0;
for (var line in lines) {
total += int.parse(line);
}
print("Total Sales: \$${total}");
}
Best Practices for File Handling
- Check file existence before access
- Use append mode for logs
- Handle exceptions properly
- Close file resources when required
- Validate data before processing
📝 Practice Exercises
Exercise 1
Create a file that stores five employee salaries and read them back.
Exercise 2
Append user login timestamps into a log file.
Exercise 3
Read a file of numbers and calculate the average value.
What’s Next?
In the next lesson, you will build a complete CLI tools project that uses files, user input, and real-time processing together.