如何在openWrite之后完成/刷新写入/关闭

时间:2013-04-08 15:33:36

标签: dart

此代码尝试打开现有文件,然后通过openWrite向其添加文本。

import 'dart:io';

main() {
  File inFile = new File('/tmp/foo.txt');
  String currentText = inFile.readAsStringSync();
  var writer = inFile.openWrite();
  writer.write(currentText);
  writer.write("\nOne more line");
  writer.close();
  exit(0);
}

完成后文件为空。如果退出(0)不存在则工作正常。 应该做什么调用以确保在退出之前写入所有写入?

1 个答案:

答案 0 :(得分:4)

由于编写器是异步的,因此在编写和关闭流时,您将希望使用编写器的done属性。例如:

import 'dart:io';

main() {
  File inFile = new File('/tmp/foo.txt');
  String currentText = inFile.readAsStringSync();
  var writer = inFile.openWrite();
  writer.write(currentText);
  writer.write("\nOne more line");
  writer.close();
  writer.done.then((_) {
    exit(0);
  });
}