Home > Mobile >  Files created in Dart cannot be read back
Files created in Dart cannot be read back

Time:07-15

I need to create an intermediary file to reprocess it later in the program. The following simple code, creates a file, writes on it and closes it and subsequently opens it for reading. The program creates the file fine, but the second part does not work. It does not give any error. Could you please help me understand what is wrong with this code. Thanks in advance for your help.

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

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
   
  var ins = new File('file1.txt').readAsLinesSync();
  for (var l in ins) {
    print(l);
  }
}

CodePudding user response:

Writing to files in Dart, in the way described in the problem, are buffered and happens asynchronously. That means that when calling close() on an IOSink, it will return a Future which completes when the file is actually closing. So if you just ignore this Future, you cannot be sure that the data are actually done being written to the disk.

I am not entirely sure if flush() is needed in this situation but the following can be found in the documentation for close():

Close the target consumer.

NOTE: Writes to the IOSink may be buffered, and may not be flushed by a call to close(). To flush all buffered writes, call flush() before calling close().

https://api.dart.dev/stable/2.17.6/dart-io/IOSink/close.html

So just to be safe, I would rewrite your solution into the following:

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

void main() async {
  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');

  await sink.flush();
  await sink.close(); // close to free resources

  var ins = new File('file1.txt').readAsLinesSync();
  for (var l in ins) {
    print(l);
  }
}
  • Related