我正在为 Firefox 制作扩展,我希望我的扩展打开一个像“file:///home/blahblah/foo.txt”这样的文件,然后将该文件的内容放入文本区域。使用文件“http://”很容易,但我不能使用“file://”来做到这一点
最佳答案
当处理本地文件时,你必须非常“大声”:
var file = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("/home/blahblah/foo.txt");
if ( file.exists() == false ) {
dup.value = “File does not exist”;
}
var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
istream.init(file, 0x01, 4, null);
var fileScriptableIO = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
fileScriptableIO.init(istream);
// parse the xml into our internal document
istream.QueryInterface(Components.interfaces.nsILineInputStream);
var fileContent = "";
var csize = 0;
while ((csize = fileScriptableIO.available()) != 0)
{
fileContent += fileScriptableIO.read( csize );
}
fileScriptableIO.close();
istream.close();
文件内容包含字符串形式的内容
关于javascript - 如何使用 URI 创建 nsIFile 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1289927/