mothorool
mothorool

Reputation:

how to create an nsIFile object using URIs

I'm making extension for firefox, and I want to my extension open a file like "file:///home/blahblah/foo.txt" and then put content of this file in text area. Its easy with files "http://", but i cant do this with "file://"

Upvotes: 1

Views: 2073

Answers (2)

Neil
Neil

Reputation: 55382

If you have the URI string for the file (rather than the local path or nsIFile object) then you can also use XMLHttpRequest to read the file's contents.

Upvotes: 0

Niko
Niko

Reputation: 6269

when working with local files you have to really "load" them:

    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 contains the content as string

Upvotes: 1

Related Questions