I want to create a file, say foo/bar/baz/bleh.html
, but none of the directories foo
, foo/bar/
, etc. exist.
How do I create my file recursively creating all of the directories along the way?
Alternatively:
new File('path/to/file').create(recursive: true);
Or:
new File('path/to/file').create(recursive: true) .then((File file) { // Stuff to do after file has been created... });
Recursive means that if the file or path doesn't exist, then it will be created. See: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.File#id_create
EDIT: This way new Directory doesn't need to be called! You can also do this in a synchronous way if you so choose:
new File('path/to/file').createSync(recursive: true);
Simple code:
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');
Here's how to create, read, write, and delete files in Dart:
Creating files:
import 'dart:io';
main() {
new File('path/to/sample.txt').create(recursive: true);
}
Reading files:
import 'dart:io';
Future main() async {
var myFile = File('path/to/sample.txt');
var contents;
contents = await myFile.readAsString();
print(contents);
}
Writing to files:
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();
}
Deleting files:
import 'dart:io';
main() {
new File('path/to/sample.txt').delete(recursive: true);
}
Note: All of the above code works properly as of Dart 2.7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With