我正在做一个项目(BrowserIO -如果你想签出代码并在上面工作,请转到browserio dot googlecode.com。欢迎帮助!)其中我使用的是火狐的nsIFileInputStream和nsIConverterInputStream,根据他们的例子(https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Simple),但只加载了完整数据的一部分。代码是:
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(path);
var data = "";
var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream);
fstream.init(file, -1, 0, 0);
cstream.init(fstream, "UTF-8", 0, 0); // you can use another encoding here if you wish
var str = {};
cstream.readString(-1, str); // read the whole file and put it in str.value
data = str.value;
cstream.close(); // this closes fstream
如果您希望看到此行为,请从BrowserIO项目页面签出代码,并使用Firebug在file_io.js中的data = str.value;
行设置断点。然后从列表中选择一个文本文件,并单击“打开”按钮。在Firebug中,在监视面板中为str.value设置监视。看看这个文件..。它应该被截断,除非它真的很短。
作为参考,上面的代码是干线/脚本/fileio.js中的openFile()函数的主体。
有谁知道这是怎么回事吗?
发布于 2009-08-26 17:00:15
参见nsIConverterInputStream;基本上,-1并不意味着“给我所有的东西”,而是“给我默认的金额”,文档声称是8192。
更广泛地说,如果您想要耗尽输入流的内容,则必须循环直到它为空。任何流契约中都没有保证调用返回的数据量是流内容的全部;如果需要,它甚至可以返回比立即可用的更少的数据量。
发布于 2009-08-26 21:55:51
我发现了如何在不进行转换的情况下读取文件,以避免因不知道文件编码类型而产生的问题。答案是在nsIFileInputStream
中使用nsIScriptableInputStream
var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
fstream.init(file, 0x01, 0004, 0);
sstream.init(fstream);
data = sstream.read(sstream.available());
https://stackoverflow.com/questions/1337303
复制