This chapter concludes how to write to a file in dart as it is very important to not only in dart but also to every programming language.
To write to files in file handling we first need to have a file to which we want to write. let’s assume we have a file named book.txt in the same directory of our dart program. It has the following text before writing. File class nad writeAsStringSync() method is used for writing to the file in this section.
Welcome to Dart File Handling.
Now, you need to write to this file in your code.
import 'dart:io'; // dart program to write to a file
void main(){
File re = File('book.txt');
re.writeAsStringSync("Welcome to Dart File Write Handling");
print("File Written");
}
If there is already somthing written in file like above than that text will change completly and will be replaced to what was written through file writing. The above example shows Writing file from text if nothing and if something than it will change. But what if you will to add text to the existing text. Then there is another mode for this which is called append mode . In this the text will conitinue to keep it like it was before and add to the exisiting code.
let’s assume we have above file book.txt having following content.
Welcome to Dart File Write Handling
Now we want to add something like “Also added from append mode to the content”. Then
import 'dart:io';
void main()
File c = File('book.txt');
re.writeAsStringSync("Also added from append mode to the content");
print("File Written without being replaced");
}