我正在尝试构建一个 Firefox 扩展,并且我想定期在文件中写入内容。所以我想要一个在其中附加新字符串的文件。以下代码写入文件,但最后文件只包含我写的最后一个字符串,而不是前一个。
你能帮助我吗?
mydir=null;
mylog=null;
mystream=null;
function initFolder() {
var dirSvc = Components.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);
有什么建议么?