Javascript写入文件没有覆盖 [英] Javascript write file without overwrite
问题描述
var string ='\\\変\\\換\\\テ\\\ス\\\ト';
file.initWithPath('C:\\temp\\temp.txt');
file.create(file.NORMAL_FILE_TYPE,0666);
var charset ='EUC-JP';
var fileStream =组件
.classes ['@ mozilla.org/network/file-output-stream; 1']
.createInstance(Components.interfaces.nsIFileOutputStream);
fileStream.init(file,2,0x200,false);
var converterStream =组件
.classes ['@ mozilla.org/intl/converter-output-stream;1']
.createInstance(Components.interfaces.nsIConverterOutputStream);
converterStream.init(fileStream,charset,string.length,
Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
converterStream.writeString(string);
converterStream.close();
fileStream.close();
所以这个代码做了以下工作。如果文件不存在,则创建它并将数据保存在其中。但是,如果文件确实存在,它将返回错误。
如果我注释到代码的一部分(和文件存在),它只会覆盖旧的数据,并把新的。
我需要这个代码来创建文件,如果它存在只是继续没有错误,并保存在新行中的数据,而不覆盖。
之前:
之前:
data11,data12,data13
data21,data22,data23
<
pre code $ data $ data $ 12 data $ $ $ $ data21 $ data $ $ data $ data31 $ data $ 32 $ data33
data41,data42,data43
在初始化输出流(而不是2)时传递 18
作为第二个参数。
fileStream.init(文件,18,0x200,false);
它将 PR_APPEND
标志添加到io模式参数(它是 0x10
; 2
用于 PR_WRONLY
)。
I am using XPCOM to read/write file(s) on my hard drive (since Java is no longer supported on FF16,17,18,+ I have to use this). I use it in my FireFox extension(s) (I use iMacros). On this document click I found this example.
var string = '\u5909\u63db\u30c6\u30b9\u30c8';
file.initWithPath('C:\\temp\\temp.txt');
file.create(file.NORMAL_FILE_TYPE, 0666);
var charset = 'EUC-JP';
var fileStream = Components
.classes['@mozilla.org/network/file-output-stream;1']
.createInstance(Components.interfaces.nsIFileOutputStream);
fileStream.init(file, 2, 0x200, false);
var converterStream = Components
.classes['@mozilla.org/intl/converter-output-stream;1']
.createInstance(Components.interfaces.nsIConverterOutputStream);
converterStream.init(fileStream, charset, string.length,
Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
converterStream.writeString(string);
converterStream.close();
fileStream.close();
So this code does the following. If file doesn't exist it creates it and saves the data in it. However if file does exists it will return error. If I comment that part of the code (and file exists) it will just overwrite the old data and put the new.
I need this code to create file, if it exists just move on without an error and save the data in the new line without overwriting.
Like this.
before:
data11, data12, data13
data21, data22, data23
after:
data11, data12, data13
data21, data22, data23
data31, data32, data33
data41, data42, data43
Try passing 18
as the second parameter when you init the output stream (instead of 2).
fileStream.init(file, 18, 0x200, false);
That adds the PR_APPEND
flag to the io mode parameter (it's 0x10
; the 2
is for PR_WRONLY
).
这篇关于Javascript写入文件没有覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!