Reading a file Asynchronously with ActionScript 3

Sometimes (okay, manytimes) files are large enough that the process of opening and reading its contents may take some time. To solve issues related to the extra time this may take AS3 allows you to open files asynchronously. I’d like to add to the information from the reading files with AS3 post. Here we’ll cover the code necessary to open a file asynchronously and read the file contents as they become available.

Because we are now doing something asynchronously, we will be dealing with events. As the file contents are being read The FileStream object broadcasts progress events that we can listen for and respond to. This ensures that when we are reading data when the data is available.

So, onto the code:
[as]
// 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

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

_fileStream.openAsync(myFile, FileMode.READ); // Call the openAsync() method instead of open()
}

private function onFileProgress(p_evt:ProgressEvent):void // Event handler for the PROGRESS Event
{
_fileContents += _fileStream.readMultiByte(_fileStream.bytesAvailable, “iso-8859-1”); // Read the contens of the file and add to the contents variable

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

private function onFileComplete(p_evt:Event):void // Event handler for the COMPLETE event
{
_fileStream.close(); // Clean up and close the file stream
}
[/as]

As for what all that code does – first off, import the required classes:
[as]
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;
import flash.events.ProgressEvent;
import flash.events.Event;
[/as]

Then we’ll need to create a couple variables. First, the FileStream which we’ll use to read our file and second, a String variable that we’ll use to display the file contents.
[as]
private var _fileStream:FileStream;
private var _fileContents:String;
[/as]

Now we’ll create an onCreationComplete() method. This method will handle the creationComplete event of the application to get things rolling. Inside the onCreationComplete() method we’ll need to create out File object as well as the FileStream object.
[as]
private function onCreationComplete():void // Fired when the application has been created
{
var myFile:File = File.appResourceDirectory;
myFile = myFile.resolve(“mySampleFile.txt”);

_fileStream = new FileStream();
}
[/as]

Still in the onCreationComplete() method, we’ll need to handle those events that will be dispatched while reading the file asynchronously. The events that we will handle are:

  • ProgressEvent.PROGRESS – This will fire as the bytes are read from the file into the buffer.
  • Event.COMPLETE – This will fire when all the bytes of the file have been read into the buffer.

[as]
private function onCreationComplete():void // Fired when the application has been created
{
var myFile:File = File.appResourceDirectory;
myFile = myFile.resolve(“mySampleFile.txt”);

_fileStream = new FileStream();

_fileStream.addEventListener(ProgressEvent.PROGRESS, onFileProgress)
_fileStream.addEventListener(Event.COMPLETE, onFileComplete);
}
[/as]

The final part of the onCreationComplete() method is to open the file asynchronously. Add the following line to the end of the method:
[as]
_fileStream.openAsync(myFile, FileMode.READ);
[/as]

Now to handle those events and read our file. First, we’ll deal with the PROGRESS event. Inside the onFileProgress() event handler method, we read the availableBytes from the file and add it to our String variable. Notice the second parameter of the readMultiByte() method – "iso-859-1". This specifies the content type of the file that we are reading. I’ll cover some of the other content types in a later post. So, keep an eye out for that one if you’re curious. Finally, we update the TextArea, to show we are actually reading the file.
[as]
private function onFileProgress(p_evt:ProgressEvent):void
{
_fileContents += _fileStream.readMultiByte(_fileStream.bytesAvailable, “iso-8859-1”);

fileContents_txt.text = _fileContents;
}
[/as]

We still need to clean up after ourselves, so in the onFileComplete() method, we’ll need to close out FileStream object.
[as]
private function onFileComplete(p_evt:Event):void
{
_fileStream.close();
}
[/as]

A very simple example, and it is still only text that we are reading. Next time I’d like to cover how to read different file types. So, like I said, keep an eye our for that post.

Reading a file with ActionScript 3

The ALPHA release of Apollo, Adobe’s cross-operating system runtime allows for some pretty sweet functionality:

  • Drag-and-drop support
  • Rich clipboard access
  • Desktop and system
    shortcuts

What I was excited about was the File API. The ability to access, read and write to files is something that is completely necessary in a desktop applications, not to mention, exciting to just play with in ActionScript. Its also something that allows for those Web applications that will be ported to desktop applications, to break out of the constraints of the Web (browser security etc.).

I’d like to give a simple example of the File API and get you started on the how’s. Its not that difficult, so lets get started. I’ll show you the code…then explain.

Simple File Read Example:
[as]
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;

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

var fileStream:FileStream = new FileStream(); // Create our file stream
fileStream.open(myFile, FileMode.READ);

var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); // Read the contens of the file
fileContents_txt.text = fileContents; // Display the contents. I’ve created a TextArea on the stage for display

fileStream.close(); // Clean up and close the file stream
[/as]
First, we’ll need to import the following classes:
[as]
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.filesystem.File;
[/as]
Next, we’ll need to create our File object so we can let our application know where the file we want to read exists. We’ll use the file.appResourceDeirectory to locate the file in relation to our application, then the resolve method of the File object myFile to locate the actual file.
[as]
var myFile:File = File.appResourceDirectory;
myFile = myFile.resolve(“mySampleFile.txt”);
[/as]
Now we’ll need to actually open the file using the FileStream object. So, we create a new FileStream object, then call the open() method and pass it the File object as well as the FileMode of READ.
[as]
var fileStream:FileStream = new FileStream();
fileStream.open(myFile, FileMode.READ);
[/as]
We have our file open, so lets go ahead and read the contents of the file. The file is a text file, so we’ll simple read the file contents into a String variable using the readUTFBytes() method of out FileStream object. Depending on the type of file and the contents of that file, you will want to use a different read method. Like I said, we’ll keep it simple for now. The readUTFBytes() method requires the number of bytes to read. We’ll pass the bytesAvailable property of the FileStream object for this parameter. The bytesAvailable prooperty, in this case, is the total bytes for the file. Finally set the value returned from the readUTFBytes() call equal to our String variable.
[as]
var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
[/as]
Alright! Now we have our String variable that contains the contents of our text file. From this point you can do anything you want with it. In this example, I’ve just set the text property of a TextArea to the value of our String variable

There is one final thing to do, and that is clean up. Make sure you call the close() method of the FileStream object once you are done reading the file.
[as]
fileStream.close();
[/as]
So that is all you need to get started with the File API. There are a few more things that I’d like to go into detail about, so I’ll make sure to post about reading file types other than plain text. I’d also like to create an example of opening a file asynchronously, so look for posts on these subjects soon.

Foundation ASP for Dreamweaver 8

One of the recent books that I’ve checked out is Foundation ASP for Dreamweaver 8. Since I used to teach a course similar to the content provided in this book I thought it might be something good to review and let everyone know about.

Review of ASP For DreamWeaver 8 – Book Review
Rated as 3/5 on May 29 2007 by John

3/5

The first thing that I have to say is that you’ll need to be quite familiar with databases to get going with this book. If your not you may just have to take a little extra time with that part of the code and set up. With that said I think that this is an excellent book for someone who is new to either Dreamweaver or ASP. There are great examples, some that can be ported easily to real world projects that you might be working on right now. The only negative note is that there are a few errors in the code that closer review and testing would have fixed before releasing the book. Although, it’s always good to get some debugging under your belt when learning a new programming language or tool…right?!

Microformats – Book Review

I didn’t know much about microformats, but hearing the buzz and wanting to know more about them led me to the book – Microformats Empowering Your Markup for Web 2.0.

Review of Microformats Empowering Your Markup for Web 2.0.
Rated as 4/5 on May 29 2007 by John

4/5

This book is perfect for someone like me that doesn’t know much about what microformats are or what they are used for. The book is also totally appropriate for those who are familiar with microformats, but need additional insight to their uses and place in the world of Web 2.0. The book does not limit itself to introduction level information. The Microformats book provides plenty of detailed information about the multiple formats that microformats take, where they came from as well as examples of how and when to use each of the microformats.One of the best pieces of information I gleaned from the book, was the purpose of microformats – simply put, to decentralize content. Decentralizing content allows for data to be located and aggregated by whatever means necessary for the end use or result by giving structure to the different types of data. This allows for disparate systems to more easily use the data.

I would say, even though microformats are very young, pick up this book learn what they are and how to use them then, help spread the word.

P.S. Technically, this review should use the hReview format, but what can I say…I haven’t built a plug-in for WordPress to do that yet, my apologies.

P.P.S I’ve just found an hReview plug-in and have converted all my reviews to the hReview format.

Commenting turned off?!

So, looks like I’ve had my head in the sand for a while and didn’t realize that comments were turned off. We’ll they are back on now. Sorry ’bout that if you’ve tried to comment.

Advanced ActionScript 3 with Design Patterns

I was very excited to receive the book Advanced ActionScript 3 with Design Patterns I had heard great things about the book and was not disappointed as I read through it.

I just happen to be stuck in jury duty for a full day and as I waited for the city and county of Denver to decide if they required my services I was able to read through most in the book in a morning. The really nice thing about this book is the lack of fluff. It is very direct, very to-the-point and very useful.
There were quite a few lessons that I learned (one would be typing a variable to an Interface…tre useful!) through out the book. Not to mention to the descriptions of many of the more popular design patterns around. I’d say Joey Lott and Danny Patterson have done a fine job presenting ActionScript 3 as applied to development with a focus on design patterns.
The only complaint that I have heard, is that that it can become a little repetitive. If you are very familiar with ActionScript syntax, you may want to skim many of the chapters for items that catch your eye and look to be good tips or new to you.

UPDATE Cairngen Ant Tasks 1.2 Release

Looks like Eric Feminella has released an updated version of Cairngen. Since I posted about the 1.0 release I figured that I’d let you know about the udpate as well.

New features in Cairngen 1.2:

  • Complete support for Cairngorm 2.0
  • Complete support for Cairngorm 2.1
  • Complete support for Cairngorm 2.2
  • Added logging capabilities for all targets
  • Abstracted user / project specific properties. User properties are now located in the project.properties file.

[Check it out]

ApolloRanch in Boulder CO

ApolloRanch is a mini-conference similar to ApolloCamp. Thanks to Xylem CCI (Xlyem and Creation Chamber merged on April 30th) for putting together and hosting the ApolloRanch, they’ve done a great job so far! ApolloRanch is at the Fisk Planetarium (shoot for the starts Apollo!) on the CU campus in Bolder.

Mike Chambers gave the keynote as well as a “creating your first Apollo application” presentation.

Here is a frew of the highlights:

  • Apollo Beta to be released on Labs around mid June (keep an eye on Labs)
  • Many of the missing APIs will be in the beta; drag-and-drop, clipboard
  • Philo (Adobe Media Player) Preview: Very interesting media player. RSS feed based “channels” for video contnet delivery (FLV).

Some more of the release timeline:

  • Apollo 1.0, Moxie (Flex 3.0), Philo 1.0 – late Fall early Winter
  • Apollo dot releases – first quarter 2008

Links for the sample apps

Cairngen 1.0 – Now with ANT

Eric Feminella created Cairngen as a code generation tool for Adobe Cairngorm. he developed it to do away with the redundant copy/paste work needed to create Flex applicatoins with Cairngorm and is released under the MIT license.

Cairngen 1.0 is built entirely in Ant and provides a solution for one-shot code generation of Adobe Cairngorm 2.2 classes.

I haven’t had a chance to play with Caringen 1.0, but can’t wait (I love ANT!).

Thanks Eric!