如何在Dart中尚不存在的目录结构中创建文件?

Jun*_*ont 12 dart dart-io

我想创建一个文件,说foo/bar/baz/bleh.html,但没有目录foo,foo/bar/等等存在.

如何创建我的文件以递归方式创建所有目录?

wil*_*ire 11

或者:

new File('path/to/file').create(recursive: true);
Run Code Online (Sandbox Code Playgroud)

要么:

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

递归意味着如果文件或路径不存在,那么它将被创建.请参阅:https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.File#id_create

编辑:这样就不需要调用新目录了!如果您这样选择,也可以以同步方式执行此操作:

new File('path/to/file').createSync(recursive: true);
Run Code Online (Sandbox Code Playgroud)

  • 我试图在这里得到的不同之处在于您不需要调用 new Directory 来创建不存在的目录。只需使用递归参数 true 调用 File 上的 create 方法即可。不管怎样,我觉得它看起来更干净一些 (2认同)

Pra*_*uza 9

以下是在 Dart 中创建、读取、写入和删除文件的方法:

创建文件:

import 'dart:io';

main() {
 new File('path/to/sample.txt').create(recursive: true);
}
Run Code Online (Sandbox Code Playgroud)

读取文件:

import 'dart:io';

Future main() async {
 var myFile = File('path/to/sample.txt');
 var contents;
 contents = await myFile.readAsString();
 print(contents);
}
Run Code Online (Sandbox Code Playgroud)

写入文件:

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();
}
Run Code Online (Sandbox Code Playgroud)

删除文件:

import 'dart:io';

main() {
 new File('path/to/sample.txt').delete(recursive: true);
}
Run Code Online (Sandbox Code Playgroud)

注意:从 Dart 2.7 开始,上述所有代码都可以正常工作


Jun*_*ont 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');
Run Code Online (Sandbox Code Playgroud)