File and Directory Operations

File and Directory Operations

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.

Creating a Directory

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.

Copying Files and Directories

1. Copying Files:

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.

2. Copying Directories:

import 'dart:io';

void main() {
  final sourceDir = Directory('source_directory');
  final destinationDir = Directory('destination_directory');
  
  sourceDir.copySync(destinationDir.path);
}

Moving/Renaming Files and Directories

Moving or renaming files and directories is a common operation when reorganizing or updating your application’s data. Dart makes it easy:

1. Moving/Renaming Files:

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.

2. Moving/Renaming Directories:

import 'dart:io';

void main() {
  final oldDir = Directory('old_directory');
  final newDir = Directory('new_directory');
  
  oldDir.renameSync(newDir.path);
}

Deleting Files and Directories

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.

1. Deleting Files

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.

2. Deleting Directories:

import 'dart:io';

void main() {
  final directoryToDelete = File('directory_to_delete');
  
  directoryToDelete.deleteSync(recursive : true);
}

Asynchronous deletion use delete(recursive:true) method.