0

我正在开发一个项目(BrowserIO - 如果你想查看代码并处理它,请转到 browserio dot googlecode dot com。欢迎帮助!),根据他们的示例,我正在使用 Firefox 的 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 项目页面签出代码,并使用 Firebugdata = str.value;在 file_io.js 中的行设置断点。然后从列表中选择一个文本文件,然后单击“打开”按钮。在 Firebug 中,在监视面板中为 str.value 设置监视。查看文件...它应该被截断,除非它真的很短。

作为参考,上面的代码是trunk/scripts/file_io.js中openFile()函数的主体。

有人知道这是怎么回事吗?

4

2 回答 2

2

nsIConverterInputStream;基本上,-1 并不意味着“给我一切”,而是“给我默认金额”,文档声称是 8192。

更一般地说,如果你想耗尽输入流的内容,你必须循环直到它为空。任何流契约中的任何内容都不能保证调用返回的数据量是流的全部内容;如果需要,它甚至可以返回比立即可用的更少。

于 2009-08-27T01:00:15.417 回答
0

我发现了如何在不转换的情况下读取文件,以避免不知道文件编码类型的问题。答案是使用nsIScriptableInputStreamwith nsIFileInputStream

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());
于 2009-08-27T05:55:51.293 回答