有几类方法:
1. 对本地文件:直接调用 nsIFile 中的方法,exists()。
2. 对网络文件(包括chrome文件):可利用其文件内容。
对于方法一:
//判断文件是否存在 chrome file 绝对路径均可 isFileExists2: function(aPath) { try { var theFile = this.getLocalFile(aPath); return theFile.exists(); } catch(e) { log("isFileExists2: " + e); } }, // 获取本地文件,参数传入绝对路径。返回nsILocalFile类型 getLocalFile: function(aPath) { var file = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); if(aPath) file.initWithPath(aPath); return file; },
对于方法二:
//判断文件是否存在 chrome file 绝对路径均可 isFileExists: function(aPath) { try { if (!/^file:/.test(aPath) && !/^chrome:/.test(aPath)) aPath = this.localPathToFilePath(aPath); var ioService = Components.classes["@mozilla.org/network/io-service;1"] .createInstance(Components.interfaces.nsIIOService); var channel = ioService.newChannel(aPath, null, null); var input = channel.open(); return !(channel.contentLength == -1); } catch(e) { log("isFileExists: " + e); return false; } finally { if(input) input.close(); } }, //本地路径转file路径 localPathToFilePath: function(aPath) { var theFile = this.getLocalFile(aPath); var ph = Components.classes["@mozilla.org/network/protocol;1?name=file"] .createInstance(Components.interfaces.nsIFileProtocolHandler); var fp = ph.getURLSpecFromFile(theFile); return fp; },
通常情况下,判断的文件属于本地文件时,一般都用 nsIFile,而chrome下,则需要通过 IOService 接口拿到,包括jar包里的文件也一样的。