Flex Blog

Search:
  • Home
  • Examples
    • Thumb

      Flex Examples

      Check out our Flex Examples!

    • Thumb

      Flash Builder Examples

      Check out our Flash Builder Examples!

    • Thumb

      AIR Examples

      Check out our AIR Examples!

    • Thumb

      Flex Mobile Examples

      Check out our Flex Mobile Examples!

    Adobe® Flex, Adobe® Flash Builder and Adobe® AIR are registered trademarks of Adobe Systems.
  • Components
    • Thumb

      WP Flex Contact Form

      Check out our WP Flex Contact Form!

    • Thumb

      Flash CountDown Plugin

      Check out our Flash CountDown Plugin!

    This is an overview of all our Flash/Flex based Components.
  • Jobs
  • Flex Books
  • Forum
  • Contact Us
Subscribe to Flex BlogSubscribe
  • Examples
  • iOS
Browse > Home / Examples / Save Data to File System with AIR in Flex 4

Save Data to File System with AIR in Flex 4

31 January 2010

Line Break

Author: Arjan (47 Articles) - Author Website

Arjan is a SAP Consultant specialized in ABAP and Front End development techniques like Web Dynpro, Adobe Interactive Forms, Flex and AIR. In his free time he likes to create examples for Flex-Blog and other applications using Flex, AIR and PHP. Other hobbies are movies and music. He is also the co-owner of Flex-Blog.com.


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:

  1. Using the ProgressBar with a file download in Flex
  2. Style AdvancedDataGrid depending on data example
  3. Reading & Writing files in Adobe AIR
  4. Remove Folder and File icons from Flex Tree
  5. Data Dependent decoratorClass in MobileIconItemRenderer Example

Written by Arjan · Filed Under Examples 

Was this post useful to you?

Please rate this post, follow us @ twitter, or link to this page from your website!

1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.33 out of 5)
Loading ... Loading ...

6d4ded3ccc9fbaaa9f26784da0807721delicious

Comments

3 Responses to “Save Data to File System with AIR in Flex 4”

  1. Roelof on February 1st, 2010 10:39 am

    Nice example Arjan :-) !

  2. rlip on October 12th, 2010 11:07 am

    Very helpful. Thanks!

  3. dvera on March 31st, 2011 8:05 pm

    Hi,
    please, how can I save file to anywhere in local disk?

Get Adobe Flash player

  • +1?

  • Support Flex Blog!

  • $ 13 raised
    • 2012/01/13 8:22 PM Russell Brown donated $ 3.00
    • 2011/10/31 4:43 PM Steve Dakin donated $ 5.00
    • 2011/05/11 3:37 PM Roelof Albers donated $ 5.00
  • Stay in touch!

  • Popular Tags

    • AdvancedDataGrid
    • AIR
    • ArrayCollection
    • baseColor
    • Button
    • CursorManager
    • DataGrid
    • Dynamic
    • Effects
    • File
    • FileStream
    • Flash Builder
    • Flash Builder 4
    • Flex 4
    • Flex Mobile
    • Framework
    • Icon
    • Image
    • itemRenderer
    • LinkBar
    • Mobile
    • PHP
    • ProgressBar
    • Repeater
    • Style
    • SWIZ
    • Timer
    • Tree
    • Twitter
    • ViewStack
  • Advertisements

  • Recent Posts

    • Spooky Frenzy – iPad Game
    • Fountain Example
    • Reading & Writing files in Adobe AIR
    • CheckBox in List using MobileIconItemRenderer for Flex Mobile
    • Data Dependent decoratorClass in MobileIconItemRenderer Example
    • Flex 4 Resize Effect Example
    • Jump to next field using the Focus Manager
    • Searching Data using a Class Example
    • Flex Mobile: Two finger tap gesture to toggle actionBar visibility in a View (AIR for Android)
    • TabbedMobileApplication Example in Flex Mobile (AIR for Android)
  • Categories

    • Examples
    • Guest Poster
    • iOS
  • Archives

    • September 2011
    • July 2011
    • May 2011
    • March 2011
    • February 2011
    • November 2010
    • October 2010
    • September 2010
    • August 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • January 2010
    • December 2009
    • November 2009
    • October 2009
    • March 2009
    • February 2009
  • Blogroll

    • Adobe Flex Jobs
    • NL for Business
  • Meta

    • Register
    • Log in
    • WordPress
    • XHTML

Copyright © 2010 Flex Blog · AdobeĀ® and AdobeĀ® Flex are registered trademarks of Adobe Systems.

WordPress Adobe Flex Adobe Flash Builder Adobe AIR Creative Commons License

  • Popular Posts

    • Progressbar in Datagrid Example 13 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 513 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Data Dependant Tree Icon with Tree in AdvancedDataGrid with iconFunction 8 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 58 votes, average: 5.00 out of 5 (5.00 out of 5)
    • List Directory with AIR in Flex 4 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex FlashVars in AS3 Example 7 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 57 votes, average: 5.00 out of 5 (5.00 out of 5)
    • Flex Dynamic Chart Example 4 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 54 votes, average: 5.00 out of 5 (5.00 out of 5)