Handling Different File Types in Apollo

So, I’ve finally snagged some time to whip out a post about dealing with different file types with the File API in Apollo AIR.

The contents of a file can be read into a ByteArray and manipulated there. For example if we had a simple text file we could read in its contents to a ByteArray with the following code:
var bytes:ByteArray = new ByteArray(); // Create our ByteArray that will hold our file data

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);

fileStream.readBytes(bytes, 0, fileStream.bytesAvailable);

You should see something that looks like the following image when you run this code:

If we wanted to out put some of the data in the ByteArray we could add the following:
for(var i:Number = 0; i <= 9; i++)
trace(“Byte Data: ” + ObjectUtil.toString(bytes[i]));
This would jsut output the first 9 items int he ByteArray. So, you’d see something like the following:

I asked myself, well what good is that? We’ll lets say the file you were reading was a PNG. You could figure out how to write that file data out to the PNG file format, or you could check out the AS3 libraries that has a PNG and JPEG encoder already.With that said you now have control…hold that, TOTAL control of the file as you read/write the bytes to/from a file.

In my previous posts (Reading a File & Reading a file Asynchronously), the file contents were read into a String variable. This was accomplished with the FileStream readMultiByte() method.

The readMultiByte(length:uint, charSet:String) method takes two (2) parameters:

  1. length: uint – The number of bytes to read from the stream
  2. charSet: String – The String specifying the character set to use to interpret the bytes read from the stream. I’m looking for a nice list of supported character sets, but have yet to find them. I’ll let you know when I do. For now we can use the livedoc examples of "shift-jis", "cn-gb" & "iso-8859-1".

We’ve checked out reading image data and text data, you could extend either of these to accommodate most situations. I’ll keep playing and if I run into anything I’ll be sure to add to this series.

Leave a Reply

Your email address will not be published. Required fields are marked *