Asynchronous programming and the events generated by a FileStream object opened asynchronously
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 Haxe 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:
import openfl.display.Sprite;
import openfl.events.ProgressEvent;
import openfl.filesystem.File;
import openfl.filesystem.FileMode;
import openfl.filesystem.FileStream;
import openfl.utils.ByteArray;
class AsyncOpenProgressExample extends Sprite
{
private var myFileStream:FileStream;
private var bytes:ByteArray;
public function new()
{
super();
bytes = new ByteArray();
var myFile:File = File.documentsDirectory.resolvePath("OpenFL Test/test.txt");
myFileStream = new FileStream();
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler);
myFileStream.openAsync(myFile, FileMode.READ);
}
private function progressHandler(event:ProgressEvent):Void
{
myFileStream.readBytes(bytes, 0, myFileStream.bytesAvailable);
}
}
You can read the entire data by registering for the complete
event, as in the
following code:
import openfl.display.Sprite;
import openfl.events.Event;
import openfl.filesystem.File;
import openfl.filesystem.FileMode;
import openfl.filesystem.FileStream;
class AsyncOpenCompleteExample extends Sprite
{
private var myFileStream:FileStream;
private var str:String;
public function new()
{
super();
str = "";
var myFile:File = File.documentsDirectory.resolvePath("OpenFL Test/test.txt");
myFileStream = new FileStream();
myFileStream.addEventListener(Event.COMPLETE, completed);
myFileStream.openAsync(myFile, FileMode.READ);
}
private function completed(event:Event):Void
{
str = myFileStream.readUTFBytes(myFileStream.bytesAvailable);
}
}
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.