1

我正在为 firefox 制作扩展名,我希望我的扩展名打开一个类似“file:///home/blahblah/foo.txt”的文件,然后将此文件的内容放在文本区域中。使用文件“http://”很容易,但我不能使用“file://”

4

2 回答 2

1

使用本地文件时,您必须真正“加载”它们:

    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();

fileContent 包含内容为字符串

于 2009-08-17T20:17:36.103 回答
0

如果您有文件的 URI 字符串(而不是本地路径或 nsIFile 对象),那么您还可以使用 XMLHttpRequest 来读取文件的内容。

于 2009-10-01T19:18:13.097 回答