How to read file using Dart

0
6606
How to read file using Dart

Reading file is a common task and it should be done easy in Dart programming language. In this article, I will show you how to read file using Dart language.

Read file using Dart

The first thing to remember is that, file is part of IO; hence, everything you need to handle files with Dart is through dart:io package. Take your time to look through the overview of the package before we start.

As you read the documentation, to read file using Dart, you will need to use File class.

Commonly, you will want to read file as string, like getting the input from a JSON/XML file, for example.

There are two ways to read files:

  • Read file synchronously.
  • Read file asynchronously.

1. Read file asynchronously

Look at the following code first:


void readFileAsync() {
  File file = new File('./assets/user.json'); // (1)
  Future<String> futureContent = file.readAsString(); (2)
  futureContent.then((c) => print(c)); // (3)
}

Here the explanation:

  • (1) we need to instantiate a new File instance with one parameter, that is, the path to the file storing in the system.
  • (2) the File instance does have a convenient method to return file content into a String, but not yet, it is available through the Future handle.
  • (3) finally, when file content is available, we can grab it and print out to the console.

Everything is done asynchronously.

However, in Dart, you can chain them in one line, and this is it.


void readFileAsync() {
  new File('./assets/user.json').readAsString().then((c) => print(c));
}

2. Read file synchronously

In case you really want to proceed next procedure only when file content is read completely, reading file synchronously is required.

Similar to reading file in async mode, you will need to use readAsStringSync() method to get complete file content.


void readFileSync() {
  String contents = new File('./assets/user.json').readAsStringSync();
  print(contents);
}

Since readAsStringSync() method returns a String, so just grab it directly.

Read file line-by-line

So you don’t want to read whole file content, but line-by-line?

Use this method readAsLines() and readAsLinesSync() when you want to execute in synchronous mode.


void readFileByLines() {
  File file = new File('./assets/user.json');

  // async
  file.readAsLines().then((lines) =>
    lines.forEach((l) => print(l))
  );

  // sync
  List<String> lines = file.readAsLinesSync();
  lines.forEach((l) => print(l));
}

Similar to read whole file as String, reading file line-by-line returning a List<String> that contains all lines of the input file after reading.

Read file as stream

It is a bit more complicated than previous two methods, but there will be times you will have to handle stream.

To create a stream from input file, use openRead() method. This method will return a Stream instance with List<int>, that is, all file content in integer value.


void readFileStream() {
  Stream<List<int>> stream = new File('./assets/user.json').openRead();
  StringBuffer buffer = new StringBuffer();
  stream
    .transform(utf8.decoder)
    .listen((data) {
      buffer.write(data);
    },
    onDone: () => print(buffer.toString()),
    onError: (e) => print(e));
}

Since we want to get readable content from file, we need to user Utf8Decoder to transform into Unicode string, and then we handle data via listen(onData, onDone, onError) method.

If you notice, the onData handler is called only once. It is because the input file is small enough for one time reading. If you provide a really really large file, it will be called many times until it reaches file EOL.

To make it clear, you can break stream to read line-by-line.


  stream
    .transform(utf8.decoder)
    .transform(LineSplitter())
    .listen((data) {
      print("Received: $data");
      buffer.write(data);
    },
    onDone: () => print(buffer.toString()),
    onError: (e) => print(e));

You will see that there are multiple logs Received is printed on the console for each line read.

Summary

Read file using Dart is very easy and convenient for Dart and Flutter developers, don’t you think?

If you’re beginners on Dart, you might feel hard to understand at first glance, but type above code, you will see how it works after all.

The full code of this tutorial is here on Github, https://github.com/petehouston/learn-dart/blob/master/bin/read_file.dart

Take your time to look through the code and learn.