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 / Reading & Writing files in Adobe AIR

Reading & Writing files in Adobe AIR

03 May 2011

Line Break

Author: Janez Feldin (6 Articles) - Author Website

Janez likes to experiment with flash in his own free time. His other hobbies are playing volleyball, listening to the music, watching movies and above all else, paragliding.

This is a simple example that shows you how to create new class for reading and writing text (.txt) files in Adobe AIR.

We start of creating a new AIR project and an ActionScript Class. In my case I called the Class TextFile, but you can ofcourse name it what you like. Also note that I have put this class in com.FlexBlog.data package.

You can download my sample AIR application here (View Source is enabled), or you can see full source below.

Below is the code of my TextFile class:

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
package com.FlexBlog.data
{
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;
   
    public class TextFile
    {
        public function TextFile()
        {
           
        }
       
//      Writes the value parameter to file and replaces everything that was already in file (if existed)
        public static function write(value:String,target_url:String):void
        {
            //crates the new file class from string that contains target url...
            var file:File = new File(target_url);
            //creates the new FileStream class used to actualy write/read/... the file...
            var fs:FileStream = new FileStream();
            //opens the file in write method
            fs.open(file,FileMode.WRITE);
            //writes the text in file (UTFBytes are normal text...)
            fs.writeUTFBytes(value);
            //closes the file after it is done writing...
            fs.close();
        }
       
//      function to read the text file starting with startIndex and ending with endIndex
        public static function read(target_url:String,startIndex:int = 0,endIndex:int = int.MAX_VALUE):String
        {
            var resaults:String;
            var file:File = new File(target_url);
            var fs:FileStream = new FileStream();
            //here we open the file in reading mode... you cannot write anything in the file while it is opened in this mode
            fs.open(file,FileMode.READ);
            //we move FileStream class to our startIndex, so that when we read something from the file it starts at startIndex and not at the begining of the file... ( if startIndex is 0 than that is the begining of the file)
            fs.position = startIndex;
            //we read the file and put it in resaults string...
            //we have to pass how many bytes we want to read to readUTFBytes. If we pass grater number than there are avaliable bytes we will get an error. That is why we take the minimum from bytesAvaliable and diference between start and end index...
            resaults = fs.readUTFBytes(Math.min(endIndex-startIndex,fs.bytesAvailable));
            //after we have done everything we want we need to close the file...
            fs.close();
            //returns the string containing the text from startIndex to endIndex
            return resaults;
        }
       
//      function used to append text to the end of text file. It is the same as write function, the only diference is that we open the file in APPEND mode and not WRITE. That means every time we write something AIR automatically writes that to the end of the file...
        public static function append(value:String,target_url:String):void
        {
            var file:File = new File(target_url);
            var fs:FileStream = new FileStream();
            fs.open(file,FileMode.APPEND);
            fs.writeUTFBytes(value);
            fs.close();
        }
//      function used to add text to desired position in file. It is the same as append, the diference is that we need to open file in UPDATE mode and we need to set position of our FileStream to desired position stored in startIndex parameter
        public static function update(value:String,target_url:String,startIndex:int = 0):void
        {
            var file:File = new File(target_url);
            var fs:FileStream = new FileStream();
            fs.open(file,FileMode.UPDATE);
            fs.position = startIndex;
            fs.writeUTFBytes(value);
            fs.close();
        }
    }
}

And here is the application’s mxml file, where you can see the example of how to call the functions in our class.

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
<?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/mx">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Button label="Write" bottom="10" left="87" click="write(event)"/>
    <s:Button label="Read" left="10" bottom="10" click="read(event)"/>
    <s:Button label="Update" bottom="10" left="165" click="update(event)"/>
    <s:Button label="Append" left="243" bottom="10" click="append(event)"/>
    <s:TextArea id="textArea" left="10" top="10" bottom="50" width="48%"/>
    <mx:FileSystemTree id="file_tree" right="10" width="48%" top="10" bottom="50"/>
   
    <fx:Script>
        <![CDATA[
            import com.FlexBlog.data.TextFile;
           
            import mx.utils.ObjectUtil;
           
            private function read(e:MouseEvent):void
            {
//              check if we have selected any file/folder
                if ( file_tree.selectedPath != null )
                {
//                  we create new file to check if it is the txt file...
                    var file:File = new File(file_tree.selectedPath);
                    if ( file.extension == "txt" )//we check to see if file extension is txt if not we don't do anything otherwise we execute the desired action
                    {
                        textArea.text = TextFile.read(file.url);
                    }
                }
            }
           
            private function write(e:MouseEvent):void
            {
                if ( file_tree.selectedPath != null )
                {
                    var file:File = new File(file_tree.selectedPath);
                    if ( file.extension == "txt" )
                    {
                        TextFile.write(textArea.text,file.url);
                    }
                }
            }
           
            private function update(e:MouseEvent):void
            {
                if ( file_tree.selectedPath != null )
                {
                    var file:File = new File(file_tree.selectedPath);
                    if ( file.extension == "txt" )
                    {
                        //this will append in front of the file
                        TextFile.update(textArea.text,file.url,0);
                    }
                }
            }
           
            private function append(e:MouseEvent):void
            {
                if ( file_tree.selectedPath != null )
                {
                    var file:File = new File(file_tree.selectedPath);
                    if ( file.extension == "txt" )
                    {
                        TextFile.append(textArea.text,file.url);
                    }
                }
            }
           
        ]]>
    </fx:Script>
</s:WindowedApplication>

Related posts:

  1. Adobe AIR SQLite Example
  2. Save Data to File System with AIR in Flex 4
  3. Flex Blog visits Adobe MAX 2010

Written by Janez Feldin · 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 (5 votes, average: 4.20 out of 5)
Loading ... Loading ...

a4d3f979610042747769357b527c1a95delicious

Comments

4 Responses to “Reading & Writing files in Adobe AIR”

  1. Louis on May 16th, 2011 4:53 am

    Hi, I’m using

    var file:File = File.desktopDirectory.resolvePath( “text.TXT” );

    to set the file path of the .txt file but how do I change the file path? I want the file path of .txt to be in the same folder with the .exe application..

  2. Janez Feldin on May 16th, 2011 9:58 am

    Here you go:
    File.applicationStorageDirectory—a storage directory unique to each installed AIR application
    File.applicationDirectory—the read-only directory where the application is installed (along with any installed assets)
    File.desktopDirectory—the user’s desktop directory
    File.documentsDirectory—the user’s documents directory
    File.userDirectory—the user directory

    The problem is, as you can see, that the directory where application’s exe file is is read-only for Adobe AIR. I would recomend you to use applicationStorageDirectory. It is directory located in %appdata% on windows and is meant for just what you want (storing files).

  3. Adam Zucchi on May 8th, 2013 8:20 pm

    Is it possible to save remote folder directories locally via AIR as well? Or can one only retrieve files, and would then have to create the directories locally manually as you get the remote files?

  4. Janez Feldin on May 13th, 2013 2:40 pm

    If you are talking about a directory on a web server than no. In this case you would have touse some server side script (PHP, coldfusion, asp…) to create that and call that script from adobe AIR.

    If you are talking about network drives I think it should be possible as long as you have that drive set up properly.

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)