In my last tutorial Part1 I discussed on basics of file classes File, FileMode & FileStream and also showed an example on how to point the file object to the desktop and list all the files and directories available under desktop and display the same inside the list component.
In this tutorial shall try to show on how to use FileMode.READ & FileMode.WRITEand also discuss on Asynchronous and Synchronous methods.
FileStream class has both synchronous and asynchronous
In synchronous method you cannot invoke other actions at a same time. Imagine if you are loading a huge file using synchronous method you need to wait until the file is loaded to process other actions.
Whereas in asynchronous method, these methods can run in a background allowing other actions to run at the same time and when an asynchronous actions completes it can dispatch events to the listeners on the status like if the files is loaded or if the file is read etc.
Synchronous methods
File.copyTo(), File.deleteDirectory(), File.deleteFile(), File.listDirectory(), File.moveTo(), File.moveToTrash(), FileStream.open()
Asynchronous methods
File.copyToAsync(), File.deleteDirectoryAsync(), File.deleteFileAsync(), File.listDirectoryAsync(), File.moveToAsync(), File.moveToTrashAsync(), FileStream.openAsync()
Example Usage synchronous –
var fileOpened:File = File.desktopDirectory.resolvePath("abc.txt");
var newfileStream:FileStream = new FileStream();
newfileStream.open(fileOpened, FileMode.READ);
newfileStream.writeUTFBytes("insert some text");
newfileStream.close();
Example Usage asynchronous –
var fileOpened:File = File.desktopDirectory.resolvePath("abc.txt");
var newfileStream:FileStream = new FileStream();
newfileStream.openAsync(fileOpened, FileMode.READ);
newfileStream.addEventListener(Event.COMPLETE, showContent);
private function showContent (event:Event):void{
// some actions to show content of the read file
}
If you look at the code above you get to see some less code used for synchronous compared to Asynchronous but using synchronous options for large files would delay other actions to be executed.
Lets take an example on asynchronous method
When a file is opened in asynchronous read method a complete event is sent to the listener , IOErrorEvent will be dispatched instead of complete event in case of an error while loading the file.
Example usage
var fileOpened:File = File.desktopDirectory.resolvePath("abc.txt");
var newfileStream:FileStream = new FileStream();
newfileStream.openAsync(fileOpened, FileMode.READ);
newfileStream.addEventListener(Event.COMPLETE, showContent);
newfileStream.addEventListener(IOErrorEvent.IO_ERROR, alertError);
private function showContent (event:Event):void{
// some actions to show content of the read file
}
private function alertError (event:Event):void{
// Display alert for the error
}
FileMode This class defines string constants (READ, WRITE, APPEND, UPDATE) used in the fileMode parameter of open() and openAsync() methods of FileStream class.
FileMode.READ - Opens file in read-only, the file should exist
FileMode.WRITE - Opens file in write-only, if file exists it will overwrite if not the file will be created
FileMode.APPEND - Opens file in write-only, Creates file if it does not exist, writes the the data at the end of the file
FileMode.UPDATE - Opens file for read-write, creates file if it does not exist, Data can be read and written to any location in the file
There are many methods of FileStream class related to reading and writing which is based on the data format in the file Object.To name a few readBytes, writeBytes, readMultiByte, readUTFBytes, writeUTFBytes, readUTF, writeUTF, readObject, writeObject etc.
The below examples demonstrates on how to read and write a text file to desktopDirectory
First create a text file “testfile.txt”
I have applied a filter to open only “testfile.txt” in order to avoid opening up any other files.
FileFilter class can be used to show users only types/extensions of files
Example usage of FileFilter
import flash.net.FileFilter;
private var applyFilter:FileFilter = new FileFilter("Documents", "*.pdf;*.doc;*.txt");
var fs_Directory = File.desktopDirectory;
fs_Directory.browseForOpen(”Open”,[applyFilter]);
This will show users only filetypes of pdf,doc,txt
<?xml version="1.0" encoding="utf-8"?> <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" title="Read Write File"> <mx:Script> <![CDATA[ import flash.filesystem.*; import flash.net.FileFilter; private var fs_FilePath:File; //File Object private var fs_Directory:File; //File Object to be set for desktop private var txtFilter:FileFilter = new FileFilter("testfile.txt Only", "testfile.txt"); private var fs_OpenStream:FileStream = new FileStream();//File Stream Object to read-write private function fileOpen():void { var fs_Directory = File.desktopDirectory; fs_Directory.browseForOpen("Open testfile.txt",[txtFilter]);//Ensure you have testfile.txt with some data on the desktop fs_Directory.addEventListener(Event.SELECT, fileSelected); } private function fileSelected(event:Event):void { savebtn.enabled=true; openbtn.enabled=false; fs_FilePath = event.target as File; fs_OpenStream = new FileStream(); fs_OpenStream.openAsync(fs_FilePath, FileMode.READ); fs_OpenStream.addEventListener(Event.COMPLETE, showContent);//Asynchronous method sends complete event to show content } private function showContent(event:Event):void { var contentValue:String = fs_OpenStream.readUTFBytes(fs_OpenStream.bytesAvailable);// read data to a string contenttext.text = contentValue; //set textarea 'contenttext' with value of 'contentValue' fs_OpenStream.close(); } private function fileSave():void { if (fs_FilePath) { if (fs_OpenStream != null) { fs_OpenStream.close();// closes filestream if its open } fs_OpenStream = new FileStream(); fs_OpenStream.openAsync(fs_FilePath, FileMode.WRITE); var contentValue:String = contenttext.text; fs_OpenStream.writeUTFBytes(contentValue); contenttext.text=""; fs_OpenStream.close(); savebtn.enabled=false; openbtn.enabled=true; } } ]]> </mx:Script> <mx:VBox width="100%" height="100%"> <mx:ApplicationControlBar width="100%" cornerRadius="0"> <mx:Button id="openbtn" label="open/read testfile.txt" click="fileOpen()"/> <mx:Button id="savebtn" label="write/save testfile.txt" click="fileSave()" enabled="false"/> </mx:ApplicationControlBar> <mx:TextArea id="contenttext" width="100%" height="100%"/> </mx:VBox> </mx:WindowedApplication> |
Disclaimer - The content provided is meant for learning purpose only.
www.adobeairtutorials.com is not responsible for any negative consequence that may result from using or implementing any information covered in the our tutorials or Articles.
www.adobeairtutorials.com does not guarantee/accuracy of the content contained in the site and reserves the right to correct any errors at any time without notice.

Recent Comments