My experience on my daily works... helping others ease each other

Tuesday, November 9, 2010

Reading file using AS3

Taken from http://snipplr.com/view/2937/reading-a-file-asynchronously-with-actionscript-3/
 // Imports
 import flash.filesystem.FileMode;
 import flash.filesystem.FileStream;
 import flash.filesystem.File;
 import flash.events.ProgressEvent;
 import flash.events.Event;

 // Declare the FileStream and String variables
     private var _fileStream:FileStream;

     private var _fileContents:String;

     private function onCreationComplete():void // Fired when the application has been created
      {
    var myFile:File = File.appResourceDirectory;
    // Create out file object and tell our File Object where to look for the file

    myFile = myFile.resolve("mySampleFile.txt"); // Point it to an actual file

          _fileStream = new FileStream(); // Create our file stream

          // Add our the progress event listener
          _fileStream.addEventListener(ProgressEvent.PROGRESS, onFileProgress);

         // Add our the complete event listener
         _fileStream.addEventListener(Event.COMPLETE, onFileComplete);
 
        // Call the openAsync() method instead of open()
        _fileStream.openAsync(myFile, FileMode.READ);
      }

      // Event handler for the PROGRESS Event
      private function onFileProgress(p_evt:ProgressEvent):void
      {

        // Read the contens of the file and add to the contents variable
       _fileContents += _fileStream.readMultiByte(_fileStream.bytesAvailable, "iso-8859-1");

       // Display the contents. I've created a TextArea on the stage for display
       fileContents_txt.text = _fileContents;
     
       }

      // Event handler for the COMPLETE event
      private function onFileComplete(p_evt:Event):void
      {

     _fileStream.close(); // Clean up and close the file stream

      }
Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates