DEV Community

loading...
Cover image for Learn Dart #5: Read and Write files in under 30 seconds

Learn Dart #5: Read and Write files in under 30 seconds

graphicbeacon profile image Jermaine Oppong Originally published at creativebracket.com Updated on ・2 min read

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
Enter fullscreen mode Exit fullscreen mode

See the solution in action below:

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());
  }
}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
  ..
  ..
}
Enter fullscreen mode Exit fullscreen mode

2. How to read the file line by line

We can create a stream to read 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'));
    ..
    ..
  }
..
..
Enter fullscreen mode Exit fullscreen mode

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

PORT=8080
API_KEY=lkjsk453lkslfkl5
API_USER=jermaineo
Enter fullscreen mode Exit fullscreen mode

Please leave your feedback in the comments, and let me know what you would like to see demonstrated next!

Subscribe to the Youtube channel for upcoming videos on Dart. Thanks!

Like, share and follow me 😍 for more content on Dart.

Further reading:

  1. The File class
  2. Free Dart screencasts on Egghead.io

Discussion (3)

pic
Editor guide
Collapse
sandordargo profile image
Sandor Dargo

Thanks for your article!

If I were lazy to look up the documentation myself, I'd like to extend this example by two things:

  • handling the path of a file in a proper way (so not a bare string)
  • read the contents of the file line by line
Collapse
graphicbeacon profile image
Jermaine Oppong Author

Thanks @sandordargo for your feedback. I've updated the article on those points.

Collapse
sandordargo profile image
Sandor Dargo

You're awesome, man!