Low Orbit Flux Logo 2 F

Dart Read and Write Files

It’s easy! Reading and writing files in is a relatively common operation that you generally become familiar with when learning a given language. You could easily end up working on multiple Dart projects without actually needing to do this if you are just building mobile apps or front end GUI apps. Even these projects sometimes need to read files ( config files, data to import, saved user data ). It all depends on your use case. Almost everything here is basically picked up from the official documentation ( see references below).

Reading files in Dart

Reading files in Dart is pretty easy. This is one of the most basic examples. It just reads in a file as a string and then prints the entire thing out.


import 'dart:async';
import 'dart:io';

void main() {
  new File('file1.txt').readAsString().then((String myData1) {
    print(myData1);
  });
}

Another way of reading in a file is to use a stream. This allows us to perform operations on a line by line basis. It is also good if you need to process large files that you don’t want to just pull into memory all at once. We do this by basically chaining together multiple function calls that will give us the data in the format that we wan’t. These functions handle a huge amount of the work for us.


import 'dart:io';
import 'dart:convert';
import 'dart:async';

main() {
final file = new File('file1.txt');
Stream<List<int>> inputStream = file.openRead();

inputStream
    .transform(utf8.decoder)                     // UTF-8 decoded from bytes
    .transform(new LineSplitter())               // split into lines
    .listen((String line) {                      // string for each line
        print('$line: ${line.length} bytes');    // work on a single line
      },
      onDone: () { print('File closed.'); },
      onError: (e) { print(e.toString()); });
}

Writing files in Dart

Writing to a file using Dart is almost as easy as reading a file. This is a very basic, simple example showing how to do it. It just writes a single string directly out to a file.


import 'dart:io';

void main() {
  final f1 = 'file1.txt';
  new File(f1).writeAsString('my string to write')
    .then((File file) {
      // you could do something here when done
    });
}

Another way to write a file is with a stream. This allows you to write data one line at a time. It is also really simple.


import 'dart:io';

void main() {
  var f1 = new File('file1.txt');
  var sink = f1.openWrite();
  sink.write('my line of data 1\n');
  sink.write('my line of data 2\n');
  sink.close();    // close to free resources
}

References

For more details, look here: