Wednesday, March 16, 2011

Files and directories in AIR: Part 6

In this tutorial we'll learn how to read files that are stored on the user's hard drive using AIR.

To accomplish this, we will need to use two classes: flash.filesystem.File (which is already familiar to us) and flash.filesystem.FileStream.

import flash.filesystem.File;
import flash.filesystem.FileStream;

var myFile:File = File.documentsDirectory.resolvePath("Air Examples/textfile.txt");
var fileStream:FileStream = new FileStream();

Use the FileStream's method open() to read the file:

fileStream.open(myFile, FileMode.READ);

You can now get some information about the file. For example, let's trace the bytes of the file.

trace(fileStream.readByte());

When done reading the file, remember to close() it.

fileStream.close();

The full code for that:

import flash.filesystem.File;
import flash.filesystem.FileStream;

var myFile:File = File.documentsDirectory.resolvePath("Air Examples/textfile.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(myFile, FileMode.READ);
trace(fileStream.readByte());
fileStream.close();

But why do we need to read the bytes? How do we simply see what's inside the file?

You most likely will never need to directly display the bytes of the file you want to read, this is simply an example of getting access to the file. As you may already know, files are stored in binary format. Humans don't usually think in binary - but computers do, they process binary files and then display it in understandable for humans format - as text, pictures, etc.

Just now we've learned how to access local files and read them. In the next tutorials we will find out how to actually do something with them.

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 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
Files and directories in AIR: Part 12

No comments:

Post a Comment