« AIR FileSystem Components | Main | Create Images with AIR and JPEGEncoder »
File and FileStream within AIR
| By Rich Tretola | February 25, 2008 | Print This Post
|
| 5,711 views |

Local access to the file system is what separates AIR from browser based Flex/Flash. This simple sample demonstrates how to read and write files to the local file system.
Here is the function that loads a file:
1 2 3 4 5 6 7 8 9 10 | private function loadFile():void{ var file:File = File.desktopDirectory.resolvePath("Files/" + fdg.selectedItem.name);; stream = new FileStream(); stream.open(file, FileMode.READ); var str:String = stream.readUTFBytes(stream.bytesAvailable); stream.close(); str = str.replace(File.lineEnding, "\n"); contents.text = str; fileName.text = file.name; } |
Here is the function that saves the file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | private function saveFile():void{ var myPattern:RegExp = / /g; var newFileName:String = fileName.text.replace('.txt',''); if(newFileName.length > 1){ var file:File = File.desktopDirectory.resolvePath("Files/" + newFileName.replace(myPattern,'_') + ".txt"); var stream:FileStream = new FileStream() stream.open(file, FileMode.WRITE); var str:String = contents.text; str = str.replace(/\r/g, File.lineEnding); stream.writeUTFBytes(str); stream.close(); fdg.directory = File.desktopDirectory.resolvePath("Files/"); fileName.text = ""; contents.text = ""; } else { mx.controls.Alert.show("File name is required", "Error Saving File"); } } |
Note that although this application uses File.desktopDirectory, you also have easy access within Apollo to:
File.applicationDirectory
File.applicationStorageDirectory
File.desktopDirectory
File.documentsDirectory
File.userDirectory
Here is the full source:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()" width="808" height="484" backgroundGradientColors="[#FFFFFF, #5df098]"> <mx:Script> <![CDATA[ import flash.filesystem.*; private var stream:FileStream; private function init():void{ var file:File = File.desktopDirectory.resolvePath("Files/sample.txt"); var stream:FileStream = new FileStream() stream.open(file, FileMode.WRITE); var str:String = "This is a sample file"; stream.writeUTFBytes(str); stream.close(); fdg.directory = File.desktopDirectory.resolvePath("Files/"); } private function saveFile():void{ var myPattern:RegExp = / /g; var newFileName:String = fileName.text.replace('.txt',''); if(newFileName.length > 1){ var file:File = File.desktopDirectory.resolvePath("Files/" + newFileName.replace(myPattern,'_') + ".txt"); var stream:FileStream = new FileStream() stream.open(file, FileMode.WRITE); var str:String = contents.text; str = str.replace(/\r/g, File.lineEnding); stream.writeUTFBytes(str); stream.close(); fdg.directory = File.desktopDirectory.resolvePath("Files/"); fileName.text = ""; contents.text = ""; } else { mx.controls.Alert.show("File name is required", "Error Saving File"); } } private function loadFile():void{ var file:File = File.desktopDirectory.resolvePath("Files/" + fdg.selectedItem.name);; stream = new FileStream(); stream.open(file, FileMode.READ); var str:String = stream.readUTFBytes(stream.bytesAvailable); stream.close(); str = str.replace(File.lineEnding, "\n"); contents.text = str; fileName.text = file.name; } ]]> </mx:Script> <mx:FileSystemDataGrid x="93" y="26" width="700" height="225" id="fdg" change="loadFile()"/> <mx:Label text="File name:" x="18" y="261" fontWeight="bold"/> <mx:Label x="19" y="301" text="Contents:" fontWeight="bold"/> <mx:TextInput x="89" y="259" id="fileName"/> <mx:TextArea x="89" y="300" id="contents" width="629" height="156"/> <mx:Label x="10" y="27" text="Current Files" fontWeight="bold"/> <mx:Button x="726" y="432" label="Save" click="saveFile()" icon="@Embed('assets/images/Save_icon.gif')"/> </mx:WindowedApplication> |
Share this Post
Topics: Adobe AIR |









June 7th, 2008 at 12:09 am
Can you save a of stream of a file located in a website? I want to build a multi-file downloader manager. Thanks
June 7th, 2008 at 8:10 am
I am not sure what you are asking? The FileReference class already supports multi file downloads.
June 18th, 2008 at 4:41 am
1. I want to create a file and write the data into it in flex application.
can we do this without using AIR. ?
2. I have tried the source code which you have pasted above getting error as “Unable to locate specified base class mx.core.WindowedApplication ”
What should be the fix and please let me know how can i run the above ex.
Thanks
mba_soft@rediff.com
June 18th, 2008 at 7:19 am
1. No, the flash player security of the flash player running in the browser does not allow you to access the users file system. This can only be done via AIR.
2. WindowedApplication is the root tag of AIR applications and not part of the Flex Framework, so it would not be found if you created your project as a Flex Web Application.
June 19th, 2008 at 2:35 am
Thx ..
infact my application already created as a Flex Web application.
1. should I recreate my project application type as AIR to work on file system?
2. cant i integrate AIR in my existing developed Flex Web app. ?
June 19th, 2008 at 5:02 am
1. Yes, you would need to be working in an AIR application to interact with the file system.
2. I am not sure what you mean? What are you trying to do?
June 19th, 2008 at 7:16 am
My application already built in flex framework using cairngorm.
In which we came a requirement like create a file, write the data into it and store it as (.vcal extension)vcal format on user system.
please suggest us as how can we develop this in our flex application?
Celine Reply:
April 27th, 2009 at 11:15 am
Hi,
I want to use cairngorm in my application but i didn’t understand if i need to install something and is it a plugin to add to flex builder?
Thanks for help.
Celine
June 19th, 2008 at 7:51 am
You can compile it as an AIR application by simply changing the root tag from mx:Application to mx:WindowedApplication
If you want the application to be a Flex web based app, you would need to create the .vcal file on the server using server side technology (ColdFusion, php, java, etc) and then allow the user to download the file using the FileReference class.
celine Reply:
April 27th, 2009 at 6:15 am
Hi,
I want to create an air application with flex builder to test this program and it gives me this error:
import flash.filesystem.*;
var source:File = File.desktopDirectory.resolvePath(”test.txt”);
var target:File = File.documentsDirectory.resolvePath(”AIR Test/test.txt”);
var targetParent:File = target.parent;
targetParent.createDirectory();
source.moveTo(target, true);
“Parse error at ‘\n\timport flash.filesystem.*;\n\nvar source:File = File.desktopDirectory.resolvePath(\”test.txt\”);\nvar target:File = File.documentsDirectory.resolvePath(\”AIR Test/test.txt\”);\nvar targetParent:File = target.parent;\ntargetParent.createDirectory();\nsource.moveTo(target, true);\n’.”
can you help me.
Thanks,
Celine
December 23rd, 2008 at 5:36 pm
Hello, I am a student multimedia design and one of my classes is developping RIA and Air apps with flex builder 3. For my exams next month I need to come up with an original application so I started working on a contact collector air app.
What I wanted to ask is how can I save my contact sheet (an arraycollection containing contacts of object type Contact) onto my hard drive, and open it again when I wish to continue adding contacts to it?
I hope you can help me with this because I’ve only had twelve hours of lessons but I really want to get this working.
Thank you,
Nils
Rich Tretola Reply:
December 24th, 2008 at 6:13 am
If it is an AIR application SQLite would make the most sense.
celine Reply:
April 27th, 2009 at 6:14 am
Hi,
I want to create an air application with flex builder to test this program and it gives me this error:
import flash.filesystem.*;
var source:File = File.desktopDirectory.resolvePath(”test.txt”);
var target:File = File.documentsDirectory.resolvePath(”AIR Test/test.txt”);
var targetParent:File = target.parent;
targetParent.createDirectory();
source.moveTo(target, true);
“Parse error at ‘\n\timport flash.filesystem.*;\n\nvar source:File = File.desktopDirectory.resolvePath(\”test.txt\”);\nvar target:File = File.documentsDirectory.resolvePath(\”AIR Test/test.txt\”);\nvar targetParent:File = target.parent;\ntargetParent.createDirectory();\nsource.moveTo(target, true);\n’.”
can you help me.
Thanks,
Celine
Rich Tretola Reply:
April 27th, 2009 at 7:22 am
Are you using Flex Builder 3 or greater? Did you create your project as an AIR (deploy to desktop) project and not a Flex (deploy to web project)?
Celine Reply:
April 27th, 2009 at 7:44 am
Hi,
yes i am using flex builder 3 and i have created the projetc as an air project but i think it didn’t support the ” flash.filesystem.*” librairy, did you have an idea for this?
thanks
Rich Tretola Reply:
April 27th, 2009 at 8:19 am
The only other thing I would say to check would be the compiler you are using within the project. Right click on the project and choose Properties -> Flex Compiler. Make sure it is 3.2 and that you have the AIR SDK within the path that is defined for 3.2 (in the Configure Flex SDKs window).
Celine Reply:
April 27th, 2009 at 8:34 am
Thank you Tretola,
So i have resolved the problem, it is because of the ‘import filesystem.*’ which i have written expect the action script function!!!!!!
So but i didn’t succed to create a folder in my desktop with this function:
Can you give an example of how to create a folder in my desktop”computer”,
Thanks,
celine
Rich Tretola Reply:
April 27th, 2009 at 12:49 pm
Celine,
The file will only be created if you actually write something to it with the FileStream class.
Check out the 3 part free excerpts from my book on how to use the file system:
Part 1:
http://www.insideria.com/2008/03/beginning-air-accessing-the-fi.html
Part 2:
http://www.insideria.com/2008/03/beginning-air-accessing-the-fi-1.html
Part 3:
http://www.insideria.com/2008/04/beginning-air-accessing-the-fi-2.html
March 3rd, 2009 at 10:32 am
To save results to local hard drive you have to options:
1) Save data via clipboard and catch data with some daemon running on pc
2) Save data via small server app, for example in PHP:
$outFile = “file.xml”;
$fout = fopen($outFile , ‘w’) or die(”can’t open file”);
$fileData = stripslashes($_POST["externalData"]);
fwrite($fout , $fileData );
fclose($fout);
You need to send data from your flex app to this script in POST request in “externalData” variable, then script will write it to file on server and allows you to download it (just make a next request from flex)
To load data from local disk you can do the same - get it from clipboard or upload it from server (a lot of upload scripts are known by google
)
Also you can try “drag-and-drop”, that got huge promotion by adobe, but i am not sure if it works in such conditions
May 12th, 2009 at 9:38 am
Hi
I want to ask you one question.
how I can save the stream of my camera in a file on my system storage, in video file of course??
thand you (sorry for my english)