When a file is opened asynchronously (using the
openAsync()
method),
reading and writing files are done asynchronously. As data is read
into the read buffer and as output data is being written, other
ActionScript code can execute.
This means that you need to register for events generated by
the FileStream object opened asynchronously.
By registering for the
progress
event, you can
be notified as new data becomes available for reading, as in the
following code:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.openAsync(myFile, FileMode.READ);
var str:String = "";
function progressHandler(event:ProgressEvent):void
{
str += myFileStream.readMultiByte(myFileStream.bytesAvailable, "iso-8859-1");
}
You can read the entire data by registering for the
complete
event,
as in the following code:
var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt");
var myFileStream:FileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completed);
myFileStream.openAsync(myFile, FileMode.READ);
var str:String = "";
function completeHandler(event:Event):void
{
str = myFileStream.readMultiByte(myFileStream.bytesAvailable, "iso-8859-1");
}
In much the same way that input data is buffered to enable asynchronous reading,
data that you write on an asynchronous stream is buffered and written to
the file asynchronously. As data is written to a file, the FileStream
object periodically dispatches an
OutputProgressEvent
object.
An
OutputProgressEvent
object includes a
bytesPending
property
that is set to the number of bytes remaining to be written. You
can register for the
outputProgress
event to be
notified as this buffer is actually written to the file, perhaps
in order to display a progress dialog. However, in general, it is
not necessary to do so. In particular, you may call the
close()
method
without concern for the unwritten bytes. The FileStream object will
continue writing data and the
close
event will
be delivered after the final byte is written to the file and the
underlying file is closed.