AIR Directory Listing Example
I was just playing around today trying to pick up some of the differences in AIR from Flex. The first and probably one of the reasons AIR applications can truly be considered desktop applications is the file system access. You have complete control over the file system like you would expect from an app running on the desktop. For my example app that I am writing I needed to be able to get a listing of files for a directory.
I decided to whip up an example so that I could show you just how easy it is to accomplish this task. This example is very basic but it shows you the real power and simplicity of the File class. This example has a text area and a browse button. When you click the browse button you will be able to select a directory. When the directory is selected all of the files will be displayed in the text box. It will not show you any directories and it will clear itself out when you select another directory. The image below shows a directory of files right off of my camera.
First we need to layout our application. This is pretty basic and should not look like anything ground breaking.
Now that we have the basic layout of our application we need to add a browse method. This is because we defined the click event of our browse button to call a method named browse. Everything we need to accomplish our end result resides in the flash.filesystem.File class. First we will create an instance of the file class. Then we are going to add an event listener to our file instance. What we are saying here is when the event.Select event is dispatched we want to call the onDirectorySelect method. This event will fire when a user selects a directory. Finally we call the browseForDirectory() method which pulls up the file systems browse.
In our onDirectorySelect method the first thing that needs to be done is to get a file reference to the directory. Now the event.target can be one of many things so by casting it as a File we are telling the compiler "trust me its going to be of type File". Once we have a reference to the file (directory) we can call the method getDirectoryListing(). Our work is not quite done though as this is going to return all files and directories. I wrote a quick easy method that will handle the displaying of files. First it makes sure the text box is clear. Next we are simply looping the files array. In each iteration of the array we are checking to make sure that the file is not a directory, if it is go ahead and add it to the text area.
