File I/O Operations in Dart

File I/O (Input/Output) operations in Dart allow you to read from and write to files on the filesystem. This is essential for applications that require data persistence, such as logging, configuration management, and data storage. Dart provides the dart:io library, which includes various classes and methods to handle file operations effectively.

Importing the Required Library

To work with files, import the dart:io library at the beginning of your Dart file:

import 'dart:io';

File I/O Operations Overview

1. Creating a File

You can create a new file using the File class:

void main() async {
  File file = File('newfile.txt');

  try {
    await file.create();
    print('File created successfully.');
  } catch (e) {
    print('Error: $e');
  }
}

Explanation

  • File('newfile.txt'): Creates a File object pointing to newfile.txt.
  • await file.create(): Asynchronously creates the file. If the file already exists, an error will occur.

2. Writing to a File

You can write to a file using the writeAsString() method. This method can overwrite the existing file or append data if specified.

Example: Overwriting a File

void main() async {
  File file = File('output.txt');

  try {
    await file.writeAsString('Hello, Dart!\n');
    print('Data written to file successfully.');
  } catch (e) {
    print('Error: $e');
  }
}

Example: Appending to a File

void main() async {
  File file = File('output.txt');

  try {
    await file.writeAsString('Appending this line.\n', mode: FileMode.append);
    print('Data appended to file successfully.');
  } catch (e) {
    print('Error: $e');
  }
}

3. Reading from a File

You can read the contents of a file using readAsString(), readAsLines(), or readAsBytes().

Example: Reading Entire File as a String

void main() async {
  File file = File('output.txt');

  try {
    String contents = await file.readAsString();
    print('File Contents:\n$contents');
  } catch (e) {
    print('Error: $e');
  }
}

Example: Reading File Line by Line

void main() async {
  File file = File('output.txt');

  try {
    List<String> lines = await file.readAsLines();
    print('File Lines:');
    for (var line in lines) {
      print(line);
    }
  } catch (e) {
    print('Error: $e');
  }
}

4. Checking File Existence

Before performing operations, you may want to check if a file exists:

void main() async {
  File file = File('output.txt');

  bool exists = await file.exists();
  print('File exists: $exists');
}

5. Deleting a File

You can delete a file using the delete() method:

void main() async {
  File file = File('output.txt');

  try {
    await file.delete();
    print('File deleted successfully.');
  } catch (e) {
    print('Error: $e');
  }
}

6. Renaming a File

You can rename a file using the rename() method:

void main() async {
  File file = File('output.txt');

  try {
    File newFile = await file.rename('renamed_output.txt');
    print('File renamed to: ${newFile.path}');
  } catch (e) {
    print('Error: $e');
  }
}

Handling Exceptions

When performing file operations, it’s essential to handle exceptions. Common exceptions include:

  • FileNotFoundException: Occurs if you try to read or delete a file that does not exist.
  • FileSystemException: Occurs for general file system errors, such as permission issues.

Use try-catch blocks to manage these exceptions gracefully.

Conclusion

File I/O operations in Dart using the dart:io library provide a robust way to manage file reading and writing. You can create, write, read, delete, and rename files easily. Understanding these operations is crucial for developing applications that require data persistence and management. With these tools, you can effectively handle file operations in your Dart applications.

PLAY QUIZ

Which library must you import to perform file I/O operations in Dart?

dart:async

dart:core

dart:collection

dart:io