« AIR FileSystem Components | Main | Create Images with AIR and JPEGEncoder »
File and FileStream within AIR

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:
2
3
4
5
6
7
8
9
10
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:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:
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
<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>
Topics: Adobe AIR | 31 Comments »


![[image]](http://mowser.com/img?url=http%3A%2F%2Fassets.max.adobe.com%2Fimages%2FMAX09_D125x125.jpg)




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
Reply to this comment
June 7th, 2008 at 8:10 am
I am not sure what you are asking? The FileReference class already supports multi file downloads.
Reply to this comment
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
Reply to this comment
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.
Reply to this comment
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. ?
Reply to this comment
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?
Reply to this comment
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?
Reply to this comment
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
Reply to this comment
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.
Reply to this comment
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
Reply to this comment
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
Reply to this comment
Rich Tretola Reply:
December 24th, 2008 at 6:13 am
If it is an AIR application SQLite would make the most sense.
Reply to this comment
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
Reply to this comment
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)?
Reply to this comment
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
Reply to this comment
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
Reply to this comment
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)
Reply to this comment
Rich Tretola Reply:
July 9th, 2009 at 7:29 am
You really can’t do much with Video yet. I recently did a presentation on something like this, but the video was tremendous. 25-30mb for only 5-10 second clips.
Reply to this comment
July 9th, 2009 at 6:43 am
how to read/write a remote file using flex and air file system
Reply to this comment
Rich Tretola Reply:
July 9th, 2009 at 7:31 am
From AIR, you could connect to a server by FTP. From Flex, you would need to have server side code doing the work of writing to the filesystem.
Reply to this comment
July 15th, 2009 at 2:08 pm
[...] Flex/Flash. This simple sample demonstrates how to read and write files to the local file system. VISIT THE TUTORIAL 0 people like this post. Like About Shafiul:Someone with no Dreams… Somewhere i [...]
September 6th, 2009 at 2:29 am
is it possible for air to handle large files gracefully? (200+ MB)? i’ve been trying to read in text files of this size to parse and organize data, but the program ends up freezing. instead of handling this data as a string or an array should i feed the file into a sqlite database for faster processing?
Reply to this comment
Rich Tretola Reply:
September 6th, 2009 at 7:40 am
Are you opening the file asynchronous?
var file:File = File.desktopDirectory.resolvePath(”myText.txt”);
var stream:FileStream = new FileStream();
stream.openAsync(file,FileMode.READ);
Reply to this comment
September 6th, 2009 at 11:55 am
yep
stream.openAsync(fileOpened, FileMode.READ);
i’ve added an event listener for the progress:
stream.addEventListener(ProgressEvent.PROGRESS, fileProgress);
private function fileProgress(p_evt:ProgressEvent):void {
fileContents += stream.readMultiByte(stream.bytesAvailable, File.systemCharset);
}
the program gets choppy and freezes when i try to split fileContents and put it into an array though:
var array:Array = fileContents.split(/\n/);
Reply to this comment
Rich Tretola Reply:
September 6th, 2009 at 8:00 pm
Ah, so the problem is not reading in the file, the problem is occurring after read completes and you are trying to work with the data in memory.
Reply to this comment
September 24th, 2009 at 9:12 am
@krippled
I am actually doing the exact same thing.
From my findings, you can open the file, but not display the entire thing at once.
Depending on what you are doing. (im graphing) you will need to either take a sample at a time, or find out if you can only display part of it, then unload that and display others when needed.
Reply to this comment
September 30th, 2009 at 4:52 am
Hi,
How can i use .air file with PHP or ASP.NET so i will use it online on my site.
Reply to this comment
January 4th, 2010 at 10:45 am
Hey Guys,
I tried with File.applicationStorageDirectory its working perfectly with windows and mac, that is I can read and write files on Windows and Mac.
But when I tried this with Ubuntu partition with Karmic Installation. It doesn’t save the file, What may be the issue?
Please help.
Thanks,
Jaswant
Reply to this comment