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

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');

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);

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

Tags:

Dart

Dart Io