【发布时间】:2013-03-08 09:35:48
【问题描述】:
我想创建一个文件,比如foo/bar/baz/bleh.html,但foo、foo/bar/ 等目录都不存在。
我如何创建我的文件以递归方式创建所有目录?
【问题讨论】:
我想创建一个文件,比如foo/bar/baz/bleh.html,但foo、foo/bar/ 等目录都不存在。
我如何创建我的文件以递归方式创建所有目录?
【问题讨论】:
或者:
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);
【讨论】:
create 而不是createSync。使用异步 API 并不总是更有效,因为最近的讨论表明,特别是对于不涉及耗时操作的操作(完整讨论:groups.google.com/a/dartlang.org/forum/#!topic/misc/uWy-rO5sz_k)
以下是在 Dart 中创建、读取、写入和删除文件的方法:
创建文件:
import 'dart:io';
main() {
new File('path/to/sample.txt').create(recursive: true);
}
读取文件:
import 'dart:io';
Future main() async {
var myFile = File('path/to/sample.txt');
var contents;
contents = await myFile.readAsString();
print(contents);
}
写入文件:
import 'dart:io';
Future main() async {
var myFile = File('path/to/sample.txt');
var sink = myFile.openWrite(); // for appending at the end of file, pass parameter (mode: FileMode.append) to openWrite()
sink.write('hello file!');
await sink.flush();
await sink.close();
}
删除文件:
import 'dart:io';
main() {
new File('path/to/sample.txt').delete(recursive: true);
}
注意:从 Dart 2.7 开始,上述所有代码都可以正常工作
【讨论】:
简单代码:
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');
【讨论】: