Field Notes from the Workshop · № 183 Open Source

XUL File I/O: Write Files

Joshua Doodnauth Software Engineer · Toronto
November 26, 2008 2 min read 250 words

Writing files in XUL isn’t that much harder than reading a file, in fact its very similar.  What a relief.  In my example I am appending the data “Appending Data” to my file.

function writeFile()
{
var data = “Appending Data”;

var filePath = “C:\\text.txt”;

var file = Components.classes[“@mozilla.org/file/local;1”]
.createInstance(Components.interfaces.nsILocalFile);
var foStream = Components.classes[“@mozilla.org/network/file-output-stream;1”]
                         .createInstance(Components.interfaces.nsIFileOutputStream);
file.initWithPath(filePath);
if ( file.exists() == false ) {
      alert(“File does not exist”);
}

foStream.init(file, 0x02 | 0x10, 00666, 0);
foStream.write(data, data.length);
foStream.close();
}

file – gets the nsILocalFile interface component, making file of type nsILocalFile
foStream – gets the nsIFileOutputStream interface component, inherited from nsIOutputStream, making foStream of type nsIFileOutputStream

  • init(file, file_io_flags,file_mode_flags, behavior_flags) –
OptionType
filensIFile
File_io_flags0x01Read only
0x02Write only

0x04

Read and Write
0x08Create File
0x10Append
0x20Truncate
0x40Sync
0x80Exclude
File_mode_flags00400Read by owner
00200Write by owner
00100Execute by owner
00040Read by Group
00020Write by Group
00010Execute by Group
00004Read by Others
00002Write by Others
00001Execute by Others
* Mode flags can by added to combine flag
* File_mode_flags is only applicable to UNIX based systems
Behavour_flags0Default

write(data, count) – sends the data string parameter to the output stream buffer, and writes the number of bytes according to count
close() – closes the stream

Not too difficult, but it is sure difficult to find the instructions and documentation