2013-04-08 67 views
1

此代碼嘗試打開現有文件,然後通過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)不在那裏,它工作正常。 應該進行哪些調用以確保在退出之前寫入所有寫入操作?

回答

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); 
    }); 
} 
相關問題