I'm trying to build a firefox extension and i want to write things periodically in a file. So i want a file in which i append new strings. The following code writes the file but at the end the file contains only the last string i wrote and not the previous.
Can you help me?
mydir=null;
mylog=null;
mystream=null;
function initFolder() {
var dirSvc = Com开发者_开发技巧ponents.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties);
mydir = dirSvc.get("ProfD", Components.interfaces.nsILocalFile);
mydir.append("mylogFolder");
if (!mydir.exists())
mydir.create(mydir.DIRECTORY_TYPE, 0700);
var fileName = "logFile.txt";
mylog = mydir.clone();
mylog.append(fileName);
mylog.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0777);
}
function mywriteFile(aData) {
// init stream
mystream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
try {
mystream.init(mylog, 0x02 | 0x10, 0777, 0); //these flags to append file?
} catch (e) {
dump("exception: " + e + "\n");
}
// convert to UTF-8
var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
var convertedData = converter.ConvertFromUnicode(aData);
convertedData += converter.Finish();
try {
mystream.write(convertedData, convertedData.length);
} catch (e) {
dump("exception: " + e + "\n");
}
}
function close() {
if (mystream instanceof Components.interfaces.nsISafeOutputStream) {
mystream.finish();
} else {
mystream.close();
}
}
window.addEventListener("load", function(){ initFolder(); }, false);
window.addEventListener("unload", function(){close(); }, false);
Any suggestions?
The reason the "safe" file output stream is safe is that it writes the data to a temporary file and only copies it over to the actual file when you call stream.finish(). So any existing data is lost. If you want to append you'll have to use a different component (plain old "@mozilla.org/network/file-output-stream;1" should work fine).
精彩评论