Save Data to File System with AIR in Flex 4
If you know Flex, you’re probably fimiliar with AIR (Adobe Integrated Runtime) as well. When developing AIR applications, you will get your hands on some additional functionality that can be very useful. One of which is the ability to read / write files from the file system. Combining this functionality with serialization gives you the opportunity to store data without creating databases, SQL statements etc. Check the example.
So, let’s say you want to store a list of persons without using a database. Let’s create user interface first. Just a DataGrid and two text inputs + button to add items to the collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <s:VGroup width="100%" height="100%" paddingLeft="5" paddingTop="5" paddingBottom="5" paddingRight="5"> <s:HGroup verticalAlign="middle" width="100%"> <s:Label text="First name:" fontWeight="bold"/> <s:TextInput id="firstName" width="50%"/> <s:Label text="Last name:" fontWeight="bold"/> <s:TextInput id="lastName" width="50%"/> <s:Button click="add()" label="Add"/> </s:HGroup> <mx:DataGrid id="dg" dataProvider="{persons}" width="100%" height="100%"> <mx:columns> <mx:DataGridColumn headerText="First Name" dataField="firstName"/> <mx:DataGridColumn headerText="Last Name" dataField="lastName"/> </mx:columns> </mx:DataGrid> <s:VGroup width="100%" horizontalAlign="right"> <s:Button label="Save to local file" click="save()"/> </s:VGroup> </s:VGroup> |
Some variables we’re gonna need:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <fx:Script> <![CDATA[ import flash.events.IOErrorEvent; import mx.collections.ArrayCollection; [Bindable] private var persons:ArrayCollection; private var file:File; private var fileStream:FileStream; private var fileName:String = "Collection.demo"; private var directory:String = "SimpleSaveFromAIR"; ]]> </fx:Script> |
The UI we created earlier calls two functions: add() and save(), let’s implement them.
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 | private function add():void { // New Object var person:Object = new Object(); // Set firstName person.firstName = firstName.text; // Set lastName person.lastName = lastName.text; // Add to ArrayCollection of persons persons.addItem(person); } private function save():void { // Create file object (resolve user's documents directory, add own directory and file name) file = File.documentsDirectory.resolvePath(directory + "\\" + fileName); // FileStream for writing the file fileStream = new FileStream(); // Open the file in write mode fileStream.open(file, FileMode.WRITE); // Write the ArrayCollection object of persons to the file fileStream.writeObject(persons); // Close FileStream fileStream.close(); } |
So that’s the save part, now we are going to implement a read() function that’s going to try to read the file from the file system when the application starts. If it fails, we want some demo data in the collection followed by the save() so that the file existst.
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 | private function read():void { // Get hte correct path file = File.documentsDirectory.resolvePath(directory + "\\" + fileName); // read the file if it exists if(file.exists) { // FileStream for reading the file fileStream = new FileStream(); // Open the file in read mode fileStream.open(file, FileMode.READ); // Read the ArrayCollection object of persons from the file persons = fileStream.readObject() as ArrayCollection; // Close the FileStream fileStream.close(); } else { // some sample data + save if file does not exist persons = new ArrayCollection(); var person:Object = new Object(); person.firstName = "John"; person.lastName = "Doe"; persons.addItem(person); person = new Object(); person.firstName = "Peter"; person.lastName = "Pan"; persons.addItem(person); person = new Object(); person.firstName = "Captain"; person.lastName = "Hook"; persons.addItem(person); save(); } } |
Finally the init method that calls the read() function. Remember to add this call to the initialize event of the Application.
1 2 3 4 5 | private function init():void { // Read file from local file system read(); } |
Download the AIR application here.
View source is enabled, but here’s the complete source code:
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | <?xml version="1.0" encoding="utf-8"?> <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" initialize="init()" viewSourceURL="srcview/index.html"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> <fx:Script> <![CDATA[ import flash.events.IOErrorEvent; import mx.collections.ArrayCollection; [Bindable] private var persons:ArrayCollection; private var file:File; private var fileStream:FileStream; private var fileName:String = "Collection.demo"; private var directory:String = "SimpleSaveFromAIR"; private function init():void { // Read file from local file system read(); } private function add():void { // New Object var person:Object = new Object(); // Set firstName person.firstName = firstName.text; // Set lastName person.lastName = lastName.text; // Add to ArrayCollection of persons persons.addItem(person); } private function save():void { // Create file object file = File.documentsDirectory.resolvePath(directory + "\\" + fileName); // FileStream for writing the file fileStream = new FileStream(); // Open the file in write mode fileStream.open(file, FileMode.WRITE); // Write the ArrayCollection object of persons to the file fileStream.writeObject(persons); // Close FileStream fileStream.close(); } private function read():void { // Get hte correct path file = File.documentsDirectory.resolvePath(directory + "\\" + fileName); // read the file if it exists if(file.exists) { // FileStream for reading the file fileStream = new FileStream(); // Open the file in read mode fileStream.open(file, FileMode.READ); // Read the ArrayCollection object of persons from the file persons = fileStream.readObject() as ArrayCollection; // Close the FileStream fileStream.close(); } else { // some sample data + save if file does not exist persons = new ArrayCollection(); var person:Object = new Object(); person.firstName = "John"; person.lastName = "Doe"; persons.addItem(person); person = new Object(); person.firstName = "Peter"; person.lastName = "Pan"; persons.addItem(person); person = new Object(); person.firstName = "Captain"; person.lastName = "Hook"; persons.addItem(person); save(); } } ]]> </fx:Script> <s:VGroup width="100%" height="100%" paddingLeft="5" paddingTop="5" paddingBottom="5" paddingRight="5"> <s:HGroup verticalAlign="middle" width="100%"> <s:Label text="First name:" fontWeight="bold"/> <s:TextInput id="firstName" width="50%"/> <s:Label text="Last name:" fontWeight="bold"/> <s:TextInput id="lastName" width="50%"/> <s:Button click="add()" label="Add"/> </s:HGroup> <mx:DataGrid id="dg" dataProvider="{persons}" width="100%" height="100%"> <mx:columns> <mx:DataGridColumn headerText="First Name" dataField="firstName"/> <mx:DataGridColumn headerText="Last Name" dataField="lastName"/> </mx:columns> </mx:DataGrid> <s:VGroup width="100%" horizontalAlign="right"> <s:Button label="Save to local file" click="save()"/> </s:VGroup> </s:VGroup> </s:WindowedApplication> |
Related posts:
- Using the ProgressBar with a file download in Flex
- Style AdvancedDataGrid depending on data example
- Remove Folder and File icons from Flex Tree
- Images in DataGrid depending on data
- List Directory with AIR in Flex 4
Comments
One Response to “Save Data to File System with AIR in Flex 4”
Got something to say?







Nice example Arjan
!