What is a File object? A File object is a pointer to a file or directory in the file system. For security reasons, it’s only available in AIR.
What can a File object do?
- Get specific directories, including the user directory, the user documents directory, the directory from which the application was launched, and the application directory
- Copy files and directories
- Move files and directories
- Delete files and directories (or move them to the trash)
- List the files and directories in a given directory
- Create temporary files and folders
- Create directories
- Read file information
- Get file system information
In AIR, the prerequisite for reading and writing files with FileStream is pointing a File object at the file. So how do you actually play with a File object? Feature 1: Pointing to directories and files A File object has two properties that can define a file path: nativePath and url. nativePath is the file path as used on a specific platform (mainly because Windows and Mac OS represent paths differently), while url is a unified format like “file:///c:/Sample%20directory/test.txt”. Let’s look at a few examples of pointing to directories, where items 1–7 demonstrate how to get special directories:
- var file:File = File.userDirectory; //points to the user folder
- var file:File = File.documentsDirectory; //points to the user documents folder
- var file:File = File.desktopDirectory; //points to the desktop
- var file:File = File.applicationStorageDirectory; //points to the application storage directory (see AIR’s URL schemes)
- var dir:File = File.applicationDirectory; //the application installation directory
- var dir:File = File.getRootDirectories(); //the file system root directory
- There’s one more trick: pointing to the directory that requested the launch of the application. Leaving it blank for now, will fill in later. See Capturing command line arguments for reference.
- var file:File = new File(); file.nativePath = “C:Mousebomb”; //(Windows platform) points to a specific directory; here the nativePath property is used, and “C:Mousebomb” only applies on Windows.
- var file:File = File.userDirectory; file = file.resolvePath(“Mousebomb”); //navigates to the Mousebomb directory under the user directory
- var urlStr:String = “file:///C:/Mousebomb/“; var file:File = new File() file.url = urlStr; //points to the Mousebomb directory on the C drive; here the url property is used
- /*let the user choose a directory*/ var file:File = new File(); file.addEventListener(Event.SELECT, dirSelected); file.browseForDirectory(“Select a directory”); function dirSelected(e:Event):void { trace(file.nativePath); }
Now let’s look at examples of pointing to files:
- Pointing to an explicit file path: var file:File = File.applicationStorageDirectory; file = file.resolvePath(“Flashj.txt”);
- An example using the url property: var urlStr:String = “file:///C:/Mousebomb/Flashj.txt”; var file:File = new File() file.url = urlStr;
- Of course you can also just write it like this: var urlStr:String = “file:///C: /Mousebomb/Flashj.txt”; var file:File = new File(urlStr); //spaces in the url are replaced with %20
- Using the nativePath property: var file:File = new File(); file.nativePath = “C:/ Mousebomb/Flashj.txt”;
- Or: var file:File = new File(“C:/ Mousebomb/Flashj.txt”); //(on Windows)
- Letting the user choose a file through a dialog. To implement this you need to know three methods: browseForOpen() browseForSave() browseForOpenMultiple() All three are asynchronous. browseForOpen() and browseForSave() dispatch a select event when the user chooses a file, and once a file has been chosen, the File points to the chosen file. browseForOpenMultiple() dispatches a selectMultiple event, which is of type FileListEvent and has a property holding an array of File objects pointing to the selected files. Example: var fileToOpen:File = File.documentsDirectory; selectTextFile(fileToOpen); function selectTextFile(root:File):void { var txtFilter:FileFilter = new FileFilter(“Text”, “*.as;*.css;*.html;*.txt;*.xml”); root.browseForOpen(“Open”, [txtFilter]); root.addEventListener(Event.SELECT, fileSelected); } function fileSelected(event:Event):void { trace(fileToOpen.nativePath); }
Feature 2: Copying files and directories The methods used to copy files are copyTo() and copyToAsync(); see AIR File Basics for details. The former is synchronous, the latter asynchronous. To copy a file, you need to create 2 File objects: one pointing to the original file, one pointing to the destination file. Like the two examples below: 1. Synchronous copy example: var original:File = File.documentsDirectory.resolvePath(“Mousebomb/FlashJ.txt”); var newFile:File = File.resolvePath(“Mousebomb/FlashJcn.txt”); original.copyTo(newFile, true); The second parameter true means overwrite existing files; the default value is false. If it’s set to false and the destination file already exists, AIR dispatches an IOErrorEvent. 2. Asynchronous copy example: var original = File.documentsDirectory; original = original.resolvePath(“Mousebomb/FlashJ.txt”); var destination:File = File.documentsDirectory; destination = destination.resolvePath(“FlashJ/FlashJcn.txt”); original.addEventListener(Event.COMPLETE, fileCopyCompleteHandler); original.addEventListener(IOErrorEvent.IO_ERROR, fileCopyIOErrorEventHandler); original.CopyToAsync(destination); function fileCopyCompleteHandler(event:Event):void { trace(event.target); // [object File] } function fileCopyIOErrorEventHandler(event:IOErrorEvent):void { trace(“I/O Error.”); } Feature 3: Moving files and directories The methods used to move files are moveTo() and MoveToAsync(). Not only do they look similar, their usage is exactly the same as copying files, so you can just refer to the section above. Feature 4: Deleting files and directories (or moving them to the trash) deleteFile() and deleteFileAsync() handle deletion, while moveToTrash() and moveToTrashAsync() move things to the trash. First create a File object pointing to a file or directory, then call one of the four methods; for the asynchronous ones you need to add an event listener. var file:File = File.documentsDirectory.resolvePath(“DeleteMe.txt”); file.moveToTrash(); Feature 5: Listing the files and directories in a directory You can use the getDirectoryListing() and getDirectoryListingAsync() methods to get an array of File pointers for the files and subdirectories in a directory. For example: var directory:File = File.documentsDirectory; var contents:Array = directory.getDirectoryListing(); for (var i:uint = 0; i < contents.length; i++) { trace(contents[i].name, contents[i].size); } This example outputs the file names and sizes in the user documents directory. If you use the asynchronous method, for example: var directory:File = File.documentsDirectory; directory.getDirectoryListingAsync(); directory.addEventListener(FileListEvent.DIRECTORY_LISTING, dirListHandler); function dirListHandler(event:FileListEvent):void { var contents:Array = event.files; for (var i:uint = 0; i < contents.length; i++) { trace(contents[i].name, contents[i].size); } } The directoryListing event object has a files property, which is an array of File pointers for the contents of the directory. Feature 6: Creating temporary files and folders You can use the createTempFile() and createTempDirectory() methods to create temporary files and folders. var temp:File = File.createTempFile(); //creates a temporary file in the system temp folder The createTempFile() method automatically creates a unique temporary file. The createTempDirectory () method automatically creates a unique temporary folder. You can use temporary files to temporarily store information from an application session. Since temporary files aren’t deleted automatically, you may need to have the application delete it before shutting down. Feature 7: Creating directories You can use the createDirectory() method to create a directory, for example: var dir:File = File.userDirectory.resolvePath(“Mousebomb”); dir.createDirectory(); This example creates the Mousebomb directory in the user folder; if the Mousebomb directory already exists, no action is taken. Feature 8: Reading file information The File class contains the following properties, which provide information about the file or directory a File object points to.
Property
Description
creationDate
Creation date
exists
Whether it exists
extension
Extension, or null if there is none
icon
The icon object for the file
isDirectory
Whether it’s a directory
modificationDate
Modification date
name
File name (including extension)
nativePath
The file path as used on a specific platform
parent
Parent directory; null if the File object is itself top-level
size
Size in bytes
url
Uniform Resource Locator
See AIR ActionScript 3.0 Language Reference for Adobe AIR. for details. Feature 9: Getting file system information The File class contains the following static properties, which provide useful file system information (mainly for cross-platform use):
Property
Description
File.lineEnding
The system’s line ending character
File.separator
The system’s separator (on Windows it’s , on Mac OS it’s /)
File.systemCharset
The system’s default file encoding, i.e. the character set used by the system
While we’re at it, here are the static properties of the Capabilities class:
Property
Description
Capabilities.hasIME
Whether the currently running system has an input method editor installed
Capabilities.language
The language code of the currently running system
Capabilities.os
The currently running operating system
References: http://livedocs.adobe.com/air/1/devappsflash/help.html?content=dg\_part\_6\_1.html(Files and Data) (If anything in this article is inaccurate, please point it out.)