Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 204
Juniper Belmont Avatar asked Mar 08 '13 09:03

Juniper Belmont


3 Answers

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); 
like image 111
Will Squire Avatar answered Oct 31 '22 17:10

Will Squire


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'); 
like image 37
Juniper Belmont Avatar answered Oct 31 '22 18:10

Juniper Belmont


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

like image 31
Prajwal Dsouza Avatar answered Oct 31 '22 19:10

Prajwal Dsouza