A Closer Look at Apollo`s File System API - Reading and Writing Files
(Page 3 of 5 )
The FileStream class provides methods that let your application read and write files.
Here’s the general process for reading and writing to a file:
Instantiate aFileStream object—for example:
var stream:FileStream = new FileStream();.
Call the
FileStream.open()or
FileStream.openAsync()method, passing in the
Fileobject as the
fileparameter and passing an appropriate file mode as the
fileModeparameter. For example:
stream.open(file, FileMode.READ);
For more information, see “File Open Modes” later in this chapter.
If you called theFileStream.openAsync()method, set up the appropriate event listener functions.
For more information, see “The open( ) and openAsync( ) Methods,” next.
Close the file, using theFileStream.close()method. For example:
stream.close();
Steps 3, 4, and 5 are described in more detail the sections that follow. First, here is a sample of code for reading UTF-8 text from a file synchronously:
var file:File = File.appStorageDirectory;
file = file.resolve("settings.xml");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.READ);
var data:String = stream.readUTFBytes(stream.
bytesAvailable);
stream.close();
Here is some code that reads the same data asynchronously:
var file:File = File.appStorageDirectory;
file = file.resolve("settings.xml");
var stream:FileStream = new FileStream();
stream.openAsync(file, FileMode.READ);
stream.addEventListener(Event.COMPLETE, readData);
var data:String;
private function readData(event:Event):void {
data = stream.readUTFBytes(stream.bytesAvailable);
stream.close();
}
Next: The open() and openAsync() Methods >>
More Flash Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the Apollo for Adobe Flex Developer's Pocket Guide, written by Mike Chambers, Rob Dixon and Jeff Swartz (O'Reilly, 2007; ISBN: 0596513917). Check it out today at your favorite bookstore. Buy this book now.
|
|