Saturday, December 10, 2011

Flex: Reading & Writing files in Adobe AIR (I/O)


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 of course name it what you like. Also note that I have put this class in com.tm.data package. you can see full source below.

Below is the code of my TextFile class:

package com.tm.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.

<?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);
                    /*
                      we check to see if file extension is txt if not we don't do anything 
                      otherwise we execute the desired action.
                    */
                    if ( file.extension == "txt" )
                    {
                        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>


No comments :

Post a Comment