FileWriter.fromFile constructor

FileWriter.fromFile(
  1. File file, {
  2. bool append = false,
  3. Encoding encoding = utf8,
})

Creates a new FileWriter, given the File to write to.

Parameters

  • file: The File to write to
  • append: If true, characters will be written to the end of the file rather than the beginning (default: false)
  • encoding: The character encoding to use (default: utf8)

Example

final file = File('output.txt');
final writer = FileWriter.fromFile(file);
final appendWriter = FileWriter.fromFile(file, append: true);

Throws IOException if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason.

Convenience class for writing character files.

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using FileOutputStream.

Example Usage

// Writing to a text file
final writer = FileWriter('output.txt');
try {
  await writer.write('Hello, World!');
  await writer.writeLine();
  await writer.writeLine('This is a new line.');
  await writer.flush();
} finally {
  await writer.close();
}

// Appending to existing file
final writer = FileWriter('log.txt', append: true);
try {
  await writer.writeLine('${DateTime.now()}: New log entry');
  await writer.flush();
} finally {
  await writer.close();
}

Implementation

FileWriter.fromFile(File file, {bool append = false, Encoding encoding = utf8})
    : _file = file, _append = append, _encoding = encoding;