In today’s quick tip, we will learn how easy it is to read and write files in Dart. We will use the File object of the ‘dart:io’ library to achieve this.

To follow along, generate the console-full project with stagehand:

$ mkdir my_app && cd my_app

$ stagehand console-full

See the solution in the below video:

Here’s the full solution:

import 'dart:io';



main() async {

var file = File('data.txt');

var contents;



if (await file.exists()) {

// Read file

contents = await file.readAsString();

print(contents);



// Write file

var fileCopy = await File('data-copy.txt').writeAsString(contents);

print(await fileCopy.exists());

print(await fileCopy.length());

}

}

And the source code.

Extending the example

1. How to better specify the file path

Install the path package by adding the dependency to your pubspec.yaml file:

dependencies:

path: ^1.6.2

And running pub get in your terminal.

Import this at the top of bin/main.dart and amend the path as follows:

import 'dart:io';

import 'package:path/path.dart';



void main() async {

var pathToFile = join(dirname(Platform.script.toFilePath()), '..', 'data.txt');

var file = File(pathToFile);

..

..

}

2. How to read the file line by line

We can create a read stream to process the file:

import 'dart:convert'; // Contains the `Utf8Decoder` and `LineSplitter` stream transformers

..

..

if (await file.exists()) {

// Read file

contents = StringBuffer();

var contentStream = file.openRead();



contentStream

.transform(Utf8Decoder())

.transform(LineSplitter())

.listen((String line) => contents.write(line), // Add line to our StringBuffer object

onDone: () => print(contents.toString()), // Call toString() method to receive the complete data

onError: (e) => print('[Problems]: $e'));

..

..

}

..

..

A good use case for this would be processing a file containing environment variables, like the file contents below: