as3文件操作

使用flash/flex进行air或手机应用的开发时,有时会需要对文件和文件夹进行操作,需要综合使用File,FileStream和FileMode类。
0.自定义目录:
var file:File = new File();
file.nativePath = “C://test//t.txt”;
1,写入到文件

var fileObj:File = File.documentsDirectory.resolvePath(“t.txt”);
var fs:FileStream = new FileStream();
fs.open(fileObj, FileMode.WRITE);
fs.writeUTFBytes(“hangge.com”);
fs.close();

2,更新文件内容
(1)下面例子在第5个字节开始覆写内容

var fileObj:File = File.documentsDirectory.resolvePath(“t.txt”);
var fs:FileStream = new FileStream();
fs.open(fileObj, FileMode.UPDATE);
fs.position = 5;
fs.writeUTFBytes(“.yuhang”);
fs.close();
(2)下面例子将内容添加到文件末尾

var fileObj:File = File.documentsDirectory.resolvePath(“t.txt”);
var fs:FileStream = new FileStream();
fs.open(fileObj, FileMode.APPEND);
fs.writeUTFBytes(“www.hangge.com”);
fs.close();

3,读取文件内容

var fileObj:File = File.documentsDirectory.resolvePath(“t.txt”);
var fs:FileStream = new FileStream();
fs.open(fileObj, FileMode.READ);
var str:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();

4,移动文件(重命名文件)

var originalFile:File = File.documentsDirectory.resolvePath(“t.txt”);
var newDir:File = File.applicationStorageDirectory.resolvePath(“t.txt”);
originalFile.moveTo(newDir);

5,复制文件

var originalFile:File = File.documentsDirectory.resolvePath(“t.txt”);
var newDir:File = File.applicationStorageDirectory.resolvePath(“t.txt”);
originalFile.copyTo(newDir);

6,删除文件

var fileObj:File = File.documentsDirectory.resolvePath(“t.txt”);
if(fileObj.exists){
fileObj.deleteFile();
}

7,创建文件夹

var fileDir:File = File.documentsDirectory.resolvePath(“t”);
fileDir.createDirectory();

8,移动文件夹

var originalDir:File = File.documentsDirectory.resolvePath(“t”);
var newDir:File = File.applicationStorageDirectory.resolvePath(“t”);
originalDir.moveTo(newDir);

9,复制文件夹

var originalDir:File = File.documentsDirectory.resolvePath(“t”);
var newDir:File = File.applicationStorageDirectory.resolvePath(“t”);
originalDir.copyTo(newDir);

10,删除文件夹

var fileDir:File = File.documentsDirectory.resolvePath(“t”);
if(fileDir.exists){
fileDir.deleteDirectory();
}

参考资料:
http://www.hangge.com/blog/cache/detail_502.html
https://blog.csdn.net/zdingxin/article/details/6635376