AIR的文件目录类型有以下几种:
File.userDirectory //指向用户文件夹
File.documentsDirectory //指向用户文档文件夹
File.desktopDirectory //指向桌面
File.applicationStorageDirectory //指向应用程序存储目录
File.applicationDirectory //应用程序安装目录
当我们把文件放在AIR工程目录下(例如放在当前目录下)时,通过以下方式是无法读取文件的
File.documentsDirectory.resolvePath('test.xml');
正确的读取文件方法是:
File.applicationDirectory.resolvePath('test.xml');
但是applicationDirectory目录下的文件为只读属性
(参考:http://help.adobe.com/zh_CN/AS3LCR/Flash_10.0/flash/filesystem/File.html)
如果需要删除该文件或是写入该文件,采用以上方法进行操作会报错(安全箱错误),为了解决此问题,我采用了以下方法读取文件:
var file:File=new File();
file.nativePath=File.applicationDirectory.nativePath + '//document//test.xml';
var fileStream:FileStream=new FileStream();
fileStream.open(file, FileMode.READ);
testXML=XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
fileStream.close();
删除文件时采用以下方法:
var file:File=new File();
file.nativePath=File.applicationDirectory.nativePath + '//document//test.xml';
file.deleteFile();
以下是完整例子:
test.xml(创建在项目src/document/下)
<?xml version="1.0" encoding="UTF-8"?> <statements> <statement> <name> test </name> </statement> <statement> <name> test1 </name> </statement> </statements>
FileTest.mxml
<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()"> <mx:Script> <!--[CDATA[ import mx.controls.Alert; var testXML:XML; private function init():void { var file:File=new File(); file.nativePath=File.applicationDirectory.nativePath + '//document//test.xml'; var fileStream:FileStream=new FileStream(); fileStream.open(file, FileMode.READ); testXML=XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); fileStream.close(); Alert.show(testXML.toString()); } private function deleteFile():void { var file:File=new File(); file.nativePath=File.applicationDirectory.nativePath + '//document//test.xml'; file.addEventListener(Event.COMPLETE, completeHandler) file.deleteFileAsync(); } function completeHandler(event:Event):void { Alert.show("Deleted.") } ]]--> </mx:Script> <mx:Button x="371" y="69" label="Delete file" click="deleteFile()"/> </mx:WindowedApplication>