Reading a file Asynchronously with ActionScript 3


/ Published in: ActionScript 3
Save to your folder(s)

This code shows you how to load large files using as3. This is good for loading in large files. Flash Player will fire events as the data becomes available.


Copy this code and paste it in your HTML
  1. // Imports
  2. import flash.filesystem.FileMode;
  3. import flash.filesystem.FileStream;
  4. import flash.filesystem.File;
  5. import flash.events.ProgressEvent;
  6. import flash.events.Event;
  7.  
  8. // Declare the FileStream and String variables
  9.  
  10. private var _fileStream:FileStream;
  11.  
  12. private var _fileContents:String;
  13.  
  14. private function onCreationComplete():void // Fired when the application has been created
  15.  
  16. {
  17.  
  18. var myFile:File = File.appResourceDirectory; // Create out file object and tell our File Object where to look for the file
  19.  
  20. myFile = myFile.resolve("mySampleFile.txt"); // Point it to an actual file
  21.  
  22.  
  23. _fileStream = new FileStream(); // Create our file stream
  24.  
  25. _fileStream.addEventListener(ProgressEvent.PROGRESS, onFileProgress); // Add our the progress event listener
  26.  
  27. _fileStream.addEventListener(Event.COMPLETE, onFileComplete); // Add our the complete event listener
  28.  
  29. _fileStream.openAsync(myFile, FileMode.READ); // Call the openAsync() method instead of open()
  30.  
  31. }
  32. private function onFileProgress(p_evt:ProgressEvent):void // Event handler for the PROGRESS Event
  33. {
  34. _fileContents += _fileStream.readMultiByte(_fileStream.bytesAvailable, "iso-8859-1"); // Read the contens of the file and add to the contents variable
  35.  
  36. fileContents_txt.text = _fileContents; // Display the contents. I've created a TextArea on the stage for display
  37. }
  38.  
  39. private function onFileComplete(p_evt:Event):void // Event handler for the COMPLETE event
  40.  
  41. {
  42. _fileStream.close(); // Clean up and close the file stream
  43. }

URL: http://office.realeyesmedia.com/blogs/john/index.php/2007/05/31/reading-a-file-asynchronously-with-actionscript-3/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.