admin';?>

首页 / js

本地文件操作

By admin •  2018-02-13 15:55:33 •  106次点击

function copyFile(sourcefile,destdir)
{
	// get a component for the file to copy
	var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
	if (!aFile) return false;
	// get a component for the directory to copy to
	var aDir = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
	if (!aDir) return false;
	// next, assign URLs to the file components
	aFile.initWithPath(sourcefile);
	aDir.initWithPath(destdir);

	// finally, copy the file, without renaming it
	aFile.copyTo(aDir,null);//or moveTo...
}
copyFile("/mozilla/testfile.txt","/etc");


function save(path,content)
{
    try
    {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e)
    {
        alert("Permission to save file was denied.");
    }
    var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath( path );
    if ( file.exists() == false )
    {
        //Components.interfaces.nsIFile.DIRECTORY_TYPE 表示创建文件夹
        file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
    }
    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance(Components.interfaces.nsIFileOutputStream );
    outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
    converter.charset = 'UTF-8';
    var convSource = converter.ConvertFromUnicode(content);
    var result = outputStream.write( convSource, convSource.length );
    outputStream.close();
 }
 
 //读取本地文件
 function read(path)
 {
     try
     {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
     } catch (e)
     {
        alert("Permission to read file was denied.");
     }
     var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile);
     file.initWithPath( path );
     if ( file.exists() == false ) { alert("File does not exist"); }
     var is = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance( Components.interfaces.nsIFileInputStream );
     is.init( file,0x01, 00004, null);
     var sis = Components.classes["@mozilla.org/scriptableinputstream;1"] .createInstance( Components.interfaces.nsIScriptableInputStream );
     sis.init( is );

     var s = sis.read(file.fileSize);
     var myBlob = new Blob([s]);

     var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"] .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
     converter.charset = "UTF-8";
     var output = converter.ConvertToUnicode(sis.read( sis.available() ));
     return output;
 }
 save("d://Yes.txt","这下ok了吧");
 alert(read("d://Yes.txt"));

//执行本地应用
var file = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("c:\myapp.exe");
file.launch();

//操作ini
function getIniValue (iniFile, section, prop) {
  var iniFact = Components.manager.getClassObjectByContractID(
    "@mozilla.org/xpcom/ini-parser-factory;1",
    Components.interfaces.nsIINIParserFactory
  );
  var iniParser = iniFact.createINIParser(iniFile);
  try {
    return iniParser.getString(section,prop);
  }
  catch(e) {
    return undefined;
  }
}
// Usage:
var lang = getIniValue(file,"Setting","Language");

//操作xml
var parser = new DOMParser();
//解析
var xmldoc = parser.parseFromString(xmlstr,"text/xml");

//反解析
var strXml = (new XMLSerializer()).serializeToString(xmldoc);

var xmldoc = document.implementation.createDocument("","",null);
xmldoc.async = false;
xmldoc.preserveWhiteSpace = true;
//打开
xmldoc.loadXML(xmlstr);
try
{
    xmldoc.load(xmlFile);
}catch(e)
{
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'your.xml', true);

    // If specified, responseType must be empty string or "document"
    xhr.responseType = 'document';

    // overrideMimeType() can be used to force the response to be parsed as XML
    xhr.overrideMimeType('text/xml');

    xhr.onload = function () {
      if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
           xmldoc =xhr.responseXML;
        }
      }
    };
    xhr.send(null);
} 

//查询
var xpe = new XPathEvaluator();
var childNodes = xpe.evaluate(xPath, xmldoc, null, XPathResult.ANY_TYPE, null);
for ( var i = 0; i < childNodes.length; i++ ) { 
var strXml = (new XMLSerializer()).serializeToString(childNodes[i]); 
alert( strXml );//childNodes[i].xml
 } 
//追加 
xmldoc.appendChild( oChild ); 
//写入文件 
var oFOStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream); 
var oFile = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProfD", Components.interfaces.nsILocalFile); // get profile folder 
oFile.append("extensions"); // extensions sub-directory 
oFile.append("{5872365E-67D1-4AFD-9480-FD293BEBD20D}"); // GUID of your extension 
oFile.append("myXMLFile.xml"); // filename 
oFOStream.init(oFile, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate 
(new XMLSerializer()).serializeToStream(xmldoc, oFOStream, ""); 
// rememeber, doc is the DOM tree 
oFOStream.close(); 

以上是使用js直接操作文件读写,足以应付一般业务的数据存取。如果涉及特殊的文件操作,如内存映射文件操作等,则可以开发xpcom,使用c++直接调用系统api.使用混合开发的好处是,c++ or web,什么时候方便,就用什么来开发,切换自如。开发效率不行,我们就用web,运行效率不行,我们就换c++.c++也好,web也好,都是当前最强大的开发利器,两者结合,取长补短。

https://developer.mozilla.org/en-US/docs/Archive/Add-ons/Code_snippets/File_I_O#Getting_your_extension.27s_folder
https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIINIParser
https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML
https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript



0 回复 | 直到2018-11-19 06:33添加回复

回复

登录发表 or 还没有账号?去注册

他山跨平台混合应用开发框架

现在注册 已注册请 登入

节点列表

产品发布

Windows  Linux  Android  最新进展 

经验交流

功能建议  Windows  Linux  Android  开发交流  资源分享  js  xul 

BUG反馈

Windows  Linux  Android 

学习生活

灌水乐园  大话界面