Snippet. Vala. Write Text to File with FileUtils

This Vala snippet shows how to write text to a file using FileUtils.

The FileUtils class from the GLib package is very convenient, when working with text files. To write text to file use the method set_contents of the class FileUtils. If the file does not exists, the file with the specified name and content will be created. If the file does exist, its content will be overwritten with the new text.

try{
    FileUtils.set_contents("data.txt","Hi.there");
}catch(Error e){
    stderr.printf ("Error: %s\n", e.message);
}

Note. This method will throw an error, if any problem arise. Therefore it must be surrounded with a try...catch... clause.


Updated on: 03 Dec 2024