How to create a file in a directory structure that does not yet exist in Dart?

I want to create a file, say foo/bar/baz/bleh.html , but there are no directories foo , foo/bar/ etc.

How to create a recursive file creating all directories along the way?

+6
source share
2 answers

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'); 
+6
source

As an alternative:

 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 does not exist, it will be created. See: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.File#id_create

EDIT: Thus, the new directory does not need to be called! You can also do this synchronously if you so decide:

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

All Articles