Saturday, March 26, 2011

Files and directories in AIR: Part 12

Today we'll learn about about ByteArrays and why should we use them when working with files.

A ByteArray object is, obviously, an array of bytes, stored in binary format. This means we can store whatever we want in a ByteArray - be it some text, or a picture, or a sound - anything at all, as long as it is in binary format. For example, we could have an application that lets the user create a digital drawing and then save it as a picture - you can't do that without using a ByteArray object.

Creating a ByteArray is simple:

import flash.utils.ByteArray;

var myByteArray:ByteArray = new ByteArray();

Now, myByteArray object can store binary data. It should be noted that we can work with a ByteArray object the same way we work with a file stream. That means we can read and write data to it, see the object's size in bytes (using the length property), use the bytesAvailable property to find out how many bytes are there between the currennt position and the final byte, and so on.

Let's pass a string value to the byte array as an example.

myByteArray.writeUTFBytes("this is a test text string");

Now the text is stored as binary data in the object. What's next?

When we have that ready, we can save this binary data as a file by passing the values to a FileStream.

var myFile:File = File.documentsDirectory.resolvePath("myData");
var myStream:FileStream = new FileStream();
myStream.open(myFile, FileMode.WRITE);
myStream.writeBytes(myByteArray);
myStream.close();

This is how you write binary data to a file stream to create a new file. But getting/writing the binary data itself can be done in many ways - you could read the data from a file, you could generate the data using code, or you could even write the data yourself (if you really want to).

That's all for now. Thanks for reading!

Related:

Files and directories in AIR: Part 1
Files and directories in AIR: Part 2
Files and directories in AIR: Part 3
Files and directories in AIR: Part 4
Files and directories in AIR: Part 5
Files and directories in AIR: Part 6
Files and directories in AIR: Part 7
Files and directories in AIR: Part 8
Files and directories in AIR: Part 9
Files and directories in AIR: Part 10
Files and directories in AIR: Part 11
Create a log application using XML and AIR: Part 1
Create a log application using XML and AIR: Part 2
Create a log application using XML and AIR: Part 3
Create a log application using XML and AIR: Part 4

1 comment:

Anonymous said...

great!

Post a Comment