Reading Files in Dart

Introduction to File Handling in Dart#

File handling is a key aspect of programming that allows you to work with files on the filesystem. In Dart, file handling is made easy through the dart:io library, which offers methods to read, write, and manage files efficiently.

Read File in Dart#

In this section, we’ll explore how to read a file in Dart. Assume that you have a file named test.txt in the same directory as your Dart program.

Synchronous Reading#

To read a file synchronously, use this approach:

import 'dart:io';

void readTextFileSync(String path) {
  try {
    // Read the entire file content as a string
    String content = File(path).readAsStringSync();
    print(content);
  } catch (e) {
    // Handle errors such as file not found or access issues
    print('An error occurred while reading the file: $e');
  }
}

void main() {
  String path = 'test.txt'; // File located in the same directory
  readTextFileSync(path);
}

Asynchronous Reading#

To read a binary file asynchronously:

import 'dart:io';

Future<void> readBinaryFile(String path) async {
  try {
    List<int> bytes = await File(path).readAsBytes();
    print(bytes);
  } catch (e) {
    print('Error reading file: $e');
  }
}

Error Handling#

Use try-catch blocks to handle errors such as file not found or permission issues:

try {
  // File operations
} catch (e) {
  print('Error reading file: $e');
}

By handling errors properly, you ensure that your application can manage file read operations smoothly, even when unexpected issues arise.