In this recipe, we demonstrate the three most important ways to write to a file. You can find the code in the project writing_files
.
The three ways to write to a file are discussed as follows:
io
and convert
as shown in the following code:import 'dart:io'; import 'dart:convert'; void main() {
writeAsString
as shown in the following code: final filename = 'outString.txt';
new File(filename).writeAsString('Dart is an elegant language').then((File file) {
// do something with the file.
});
writeAsBytes
as shown in the following code: final string = '你好世界';
// Encode to UTF8.
var encodedData = UTF8.encode(string);
new File('outUTF8.txt').writeAsBytes(encodedData).then((file)
=> file.readAsBytes()).then((data) {
// Decode to a string, and print.
print(data);
// [228, 189, 160, 229, 165, 189, 228, 184, 150, 231, 149, 140]
print(UTF8.decode(data)); // prints '你好世界'.
});
openWrite
as shown in the following code:var file = new File('out3.txt'), var sink = file.openWrite(); sink.write('File was written to at ${new DateTime.now()} '), // close the IOSink to free system resources! sink.close(); }
Step 1 uses the asynchronous writeAsString
method to write one (big) string to a file, and this file is then automatically closed. In the callback function called by then
, you could, for example, send the file over the network. Step 2 shows how to write raw bytes to a file with writeAsBytes
. This is necessary when the file contains non-readable or Unicode characters.
What do we do when we want to write to our file in chunks? Then, we use the openWrite
method as shown in step 3. When called on a File
object, this creates an IOSink
object for that file, which you can write to with any of the following methods: write
, writeln
, writeCharCode
, writeAll
. In contrast to the write methods of the previous steps, the IOSink
object must be explicitly closed when no longer needed. The openWrite
method takes two optional arguments as shown in the following code:
file.openWrite(mode: FileMode.APPEND, encoding: ASCII);
The default mode is FileMode.WRITE
.