Dart:
Writing a text file
How to:
Dart’s core library provides the dart:io
package for file handling, allowing you to write text files without the need for third-party libraries. Here’s a simple example of writing a text file:
import 'dart:io';
void main() async {
// Create a new file named 'example.txt' in the current directory.
var file = File('example.txt');
// Write a string to the file.
await file.writeAsString('Hello, Dart!');
// Verify the contents.
print(await file.readAsString()); // Output: Hello, Dart!
}
When dealing with larger files or streams of data, you might prefer writing content using openWrite
which returns an IOSink
and allows you to write data in chunks:
import 'dart:io';
void main() async {
var file = File('large_file.txt');
var sink = file.openWrite();
// Write multiple lines to the file.
sink
..writeln('Line 1: The quick brown fox jumps over the lazy dog.')
..writeln('Line 2: Dart is awesome!')
..close();
// Wait for the sink to close to ensure all data is written to the file.
await sink.done;
// Read and print file content to verify
print(await file.readAsString());
}
For more advanced file operations, including appending to files or writing bytes, you may delve deeper into the File
class methods provided by dart:io
. Additionally, when working on large scale or more complex projects, considering packages like path
for dealing with file paths or shelf
for web server functionalities might be beneficial, though direct file writing typically relies on the built-in Dart libraries.