【问题标题】:how to create an nsIFile object using URIs如何使用 URI 创建 nsIFile 对象
【发布时间】:2009-08-17 19:31:44
【问题描述】:

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

【问题讨论】:

  • 你是说你有一个文件:你想从中加载的 URI,你需要一个 nsIFile 对象吗?

标签: javascript firefox-addon mozilla xpcom


【解决方案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 包含字符串形式的内容

【讨论】:

【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2011-11-07
    • 2020-07-02
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多