注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

无线时代辐射无穷

抓紧生宝宝,小心辐射

 
 
 

日志

 
 

在flex4中保存数据到文件系统  

2011-06-03 10:24:51|  分类: flex |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
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
Reading & Writing files in Adobe AIR
Remove Folder and File icons from Flex Tree
Data Dependent decoratorClass in MobileIconItemRenderer Example
  评论这张
 
阅读(746)| 评论(1)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017