2013-03-08 86 views

回答

6

簡單代碼:

import 'dart:io'; 

void createFileRecursively(String filename) { 
    // Create a new directory, recursively creating non-existent directories. 
    new Directory.fromPath(new Path(filename).directoryPath) 
     .createSync(recursive: true); 
    new File(filename).createSync(); 
} 

createFileRecursively('foo/bar/baz/bleh.html'); 
+0

我很好奇你如何指定這些目錄的文件權限。它不會出現,它們必然會從父項繼承。 – sager89 2016-10-19 19:39:07

3

或者:

new File('path/to/file').create(recursive: true); 

或者:

new File('path/to/file').create(recursive: true) 
.then((File file) { 
    // Stuff to do after file has been created... 
}); 

遞歸意味着,如果文件或路徑不存在,那麼它會被創建。見:https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.File#id_create

編輯:這種方式新的目錄不需要被調用!你也可以用同步的方式做到這一點,如果你這樣選擇:

new File('path/to/file').createSync(recursive: true); 
+0

這與@JuniperBelmont的基本相同,區別在於使用'create'而不是'createSync'。使用異步API並不總是更有效,因爲最近的討論特別針對不涉及耗時操作的操作(完整討論:https://groups.google.com/a/dartlang.org/forum/#! topic/misc/uWy-rO5sz_k) – 2014-10-11 14:17:02

+0

我試圖在這裏得到的區別是你不需要調用新目錄來創建不存在的目錄。只需在遞歸參數爲true的情況下調用File的create方法即可。無論如何,我認爲它看起來有點清潔 – willsquire 2014-10-11 14:45:19

+0

哈哈,改進! – willsquire 2014-10-11 14:57:14

相關問題