这几天一直都在用Firefox处理文件,在Firefox中,不管是任何文件,是txt,json还是任何数据类型的文件,其实都是文本文件,(不过推荐用txt和json,可序列化而且方便操作)所以这里就要经常使用文件进行处理。而每次写插件的时候都要调用一些XPCOM,获取系统环境来进行操作,实在是太麻烦,所以就封装了一个File类方便在扩展中使用。
由于我比较喜欢C#的命名,非常优雅和好读,所以就按照C#的命名来命名我的类,使用方法如下。
首先,添加引用,这里注意顺序正反可能会有问题,所以最好把IO放到上面。
<script src="System.File.IO.js"/>
<script src="System.File.js"/>
<script src="System.File.js"/>
在引用后,我们可以使用我们声明的对象了,代码如下所示。
//文件操作类
//net.ff.file
//文件夹操作类
//net.ff.diectory
var file = new net.ff.file();
var diectory = new net.ff.diectory();
//net.ff.file
//文件夹操作类
//net.ff.diectory
var file = new net.ff.file();
var diectory = new net.ff.diectory();
我们在声明了两个类之后,就能够使用相应的方法了,这些方法和含义如下。
//file类,操作文件
//判断是否为Windows
IsWindows:function()
//获取系统信息
GetSysInfo:function()
//返回文件内容
ReadToEnd:function(path)
//覆盖写文件
Write:function(path,comment)
//增加的按行写文件
WriteLine:function(path,comment)
//附加文件
AppendText:function(path,comment)
//删除文件
Delete:function(path)
//判断是否存在文件
IsExist:function(path) //diectory类,操作文件夹
//一般文件都会被创建在当前profile里面
//只要传递文件夹的名称即可,其他的不用关心
Create:function(foldername)
Delete:function(foldername)
IsExist:function(foldername)
//这个是获取相应的文件夹的路径
GetDiectory:function(foldername)
//判断是否为Windows
IsWindows:function()
//获取系统信息
GetSysInfo:function()
//返回文件内容
ReadToEnd:function(path)
//覆盖写文件
Write:function(path,comment)
//增加的按行写文件
WriteLine:function(path,comment)
//附加文件
AppendText:function(path,comment)
//删除文件
Delete:function(path)
//判断是否存在文件
IsExist:function(path) //diectory类,操作文件夹
//一般文件都会被创建在当前profile里面
//只要传递文件夹的名称即可,其他的不用关心
Create:function(foldername)
Delete:function(foldername)
IsExist:function(foldername)
//这个是获取相应的文件夹的路径
GetDiectory:function(foldername)
知道了这些基本的方法,就可以使用了,示例代码如下。
var dir= new net.ff.diectory();
var file = new net.ff.file();
//创建文件夹
dir.Create("myfolder");
//获取文件的完整路径
var path = dir.GetDiectory("myfolder") + "\\" + "test.txt";
//写文件
file.Write(path,‘test‘);
file.WriteLine(path,‘tester2‘);
//读文件
alert(cf.ReadToEnd(path));
var file = new net.ff.file();
//创建文件夹
dir.Create("myfolder");
//获取文件的完整路径
var path = dir.GetDiectory("myfolder") + "\\" + "test.txt";
//写文件
file.Write(path,‘test‘);
file.WriteLine(path,‘tester2‘);
//读文件
alert(cf.ReadToEnd(path));
这样我们的代码就非常轻便了,不需要再过多的关系底层XPCOM的东西。
当然,我这个类可能写的不是特别好,凑合用就行了,不过自我感觉还可以。。嘿嘿。。
[...] Firefox Add-on – 自己封装的File类 [...]