XUL File I/O: Write Files
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) –
| Option | Type | |
| file | nsIFile | |
| File_io_flags | 0x01 | Read only |
| 0x02 | Write only | |
0x04 | Read and Write | |
| 0x08 | Create File | |
| 0x10 | Append | |
| 0x20 | Truncate | |
| 0x40 | Sync | |
| 0x80 | Exclude | |
| File_mode_flags | 00400 | Read by owner |
| 00200 | Write by owner | |
| 00100 | Execute by owner | |
| 00040 | Read by Group | |
| 00020 | Write by Group | |
| 00010 | Execute by Group | |
| 00004 | Read by Others | |
| 00002 | Write by Others | |
| 00001 | Execute by Others | |
| * Mode flags can by added to combine flag * File_mode_flags is only applicable to UNIX based systems | ||
| Behavour_flags | 0 | Default |
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
great stuff….very informative…thanks…