Cheshie
Cheshie

Reputation: 2837

How do I concatenate string to an existing file?

I've got a text file (it has content in it) and I want to append text to it. This is my code:

File outputFile=new File('hello.out');
      outputFile.createSync();
      List<String> readLines=files[i].readAsLinesSync(Encoding.UTF_8);
      for(int j=0;j<readLines.length;j++)
      {

        outputFile.writeAsStringSync(readLines[j], FileMode.APPEND); }

For some reason Dart put a yellow line under "FileMode.APPEND" and it says that it's an "extra argument". However, this link http://api.dartlang.org/docs/releases/latest/dart_io/File.html claims that it is optional.

Upvotes: 11

Views: 6360

Answers (2)

plowman
plowman

Reputation: 13585

The FileMode is an optional, named parameter, so you have to specify its name ('mode') when you call it. To solve your problem, change this:

outputFile.writeAsStringSync(readLines[j], FileMode.append);

to this:

outputFile.writeAsStringSync(readLines[j], mode: FileMode.append);

Upvotes: 18

Kai Sellgren
Kai Sellgren

Reputation: 30212

This code is really all you need:

import 'dart:io';

main() {
  new File('test.txt').writeAsStringSync('append some more content', mode: FileMode.APPEND);
}

Notice that the file mode is a named parameter, so you need to specify it as mode:.

And as always, use the asynchronous version unless it doesn't matter (cli tools, one-time initialization during start-up, etc.)

Upvotes: 5

Related Questions