File and directory operations in Dart are essential for managing your application’s data, organizing resources, and ensuring efficient file handling. Dart provides a rich set of methods to perform operations like creating, copying, moving, listing and deleting files and directories.
import 'dart:io';
void createDirectory(String path) async{
final directory = Directory(path);
if(!await directory.exists()){
await directory.create(recursive:true);
print('Directory created: $path');
}else{
print('Directory already exists: $path');
}
}
void main() {
createDirectory('example_directory');
}
Asynchronous creation of directory use create(recursive:true) method while createSync() is used for synchronous creation.
import 'dart:io';
void main() {
final sourceFile = File('source.txt');
final destinationFile = File('destination.txt');
sourceFile.copySync(destinationFile.path);
}
The copySync() method copies the file from one file i.e ( source ) to another file ( destination ) synchronously. The copy() method is used for asynchronous copying.
import 'dart:io';
void main() {
final sourceDir = Directory('source_directory');
final destinationDir = Directory('destination_directory');
sourceDir.copySync(destinationDir.path);
}
Moving or renaming files and directories is a common operation when reorganizing or updating your application’s data. Dart makes it easy:
import 'dart:io';
void main() {
final oldFile = File('old.txt');
final newFile = File('new.txt');
oldFile.renameSync(newFile.path);
}
The renameSync() method renames the old file to the new file synchronously. The rename() method is used for asynchronous renaming.
import 'dart:io';
void main() {
final oldDir = Directory('old_directory');
final newDir = Directory('new_directory');
oldDir.renameSync(newDir.path);
}
Deleting unnecessary files and directories is a cruical operation to help to manage disk space and keep your application tidy and improve performance on device.
import 'dart:io';
void main() {
final fileToDelete = File('file_to_delete.txt');
fileToDelete.deleteSync();
}
The deleteSync methods is used for deleting file synchronously. The delete() method is used for asynchronous deletion.
import 'dart:io';
void main() {
final directoryToDelete = File('directory_to_delete');
directoryToDelete.deleteSync(recursive : true);
}
Asynchronous deletion use delete(recursive:true) method.