如何在Dart中尚不存在的目录结构中创建文件?
我想创建一个文件,说foo/bar/baz/bleh.html
,但目录foo
,foo/bar/
等都不存在。如何在Dart中尚不存在的目录结构中创建文件?
如何创建我的文件递归创建沿途的所有目录?
简单代码:
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');
或者:
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);
这与@JuniperBelmont的基本相同,区别在于使用'create'而不是'createSync'。使用异步API并不总是更有效,因为最近的讨论特别针对不涉及耗时操作的操作(完整讨论:https://groups.google.com/a/dartlang.org/forum/#! topic/misc/uWy-rO5sz_k) – 2014-10-11 14:17:02
我试图在这里得到的区别是你不需要调用新目录来创建不存在的目录。只需在递归参数为true的情况下调用File的create方法即可。无论如何,我认为它看起来有点清洁 – willsquire 2014-10-11 14:45:19
哈哈,改进! – willsquire 2014-10-11 14:57:14
我很好奇你如何指定这些目录的文件权限。它不会出现,它们必然会从父项继承。 – sager89 2016-10-19 19:39:07