A Closer Look at Apollo`s File System API - The open() and openAsync() Methods (Page 4 of 5 )
Your application needs to open a file before it can read from or write to the file.
When you open a file with theFileStream.openAsync()method, the file is opened for asynchronous operations, and you’ve registered event listeners to monitor progress.
TheFileStream.open()method opens the file for synchronous operations. If your application opens the file using this synchronous method, all subsequent calls to methods that read or write to the file will be done synchronously as well. In the following example, each of the calls tostream.open(),stream.writeUTFBytes(), andstream.close()will complete before the next call is made.
var newFile:File = File.documentsDirectory; file = file.resolve("ApolloTest/test.txt");
var stream:FileStream = new FileStream() stream.open(file, FileMode.WRITE); stream.writeUTFBytes("This is some sample text."); stream.close();
The advantage of opening a file for synchronous operations is that you can write less code to complete a task. The disadvantage is that execution of other ActionScript code can be delayed if the file operations take a while. As a result, if you are working with large files or opening files that are shared on slow networks, you should consider using theFileStream.openAsync()method instead.
When you use theopenAsync()method, the following processes are all handled asynchronously:
Closing the file
TheFileStream object dispatches acloseevent when the file is closed.
Reading data into the read buffer
TheFileStreamobject dispatchesprogressevents as data is read, and it dispatches acompleteevent once all the data is read. However, once data is read, calling a read method (such asreadBytes()) to read data is a synchronous process.
I/O errors
TheFileStream object dispatches anioErrorevent upon encountering an error. This may occur for a number of reasons, such as attempting to open a file that doesn’t exist or attempting to write to a file that is locked. However, some errors, such as attempting to read from a file that has not been opened, throw exceptions (rather than dispatchioErrorevents) because the Apollo runtime can detect the error condition instantly.
Before calling theFileStream.openAsync()method, your application should set up event listener functions to handle those events in which it is interested.
The following example opens a file in asynchronous read mode. After the file has been opened, the complete event will be dispatched (unless there is an error, in which case theioErrorevent will be dispatched instead). ThecompleteHandler()method then calls theFileStream.readBytes()method, which starts reading data from the file as an array of bytes, in asynchronous mode. When all the bytes have been read from the file, thecompleteevent will be dispatched:
var file:File = File.documentsDirectory. resolve("ApolloTest/test.txt"); var stream:FileStream = new FileStream();