Quick Start Examples:
Example 1. Reading XML var testXML:XML; var file:File = File.documentsDirectory.resolvePath(“Mousebomb/test.xml”); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); testXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); fileStream.close(); The example uses the readUTFBytes() method to read the content and convert it into an XML object.
Example 2. Writing XML var testXML:XML =www.mousebomb.orgwww.flashj.cn; var file:File = File.documentsDirectory.resolvePath(“Mousebomb/test.xml”); var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.WRITE); var outputString:String = ‘’; outputString += testXML.toXMLString(); fileStream.writeUTFBytes(outputString); fileStream.close(); Writing XML is just as simple: create a File object and a FileStream object, then use writeUTFBytes() to write the data.
Workflow
Reading and writing files basically comes down to these steps: 1. Create a File object pointing to the file path 2. Initialize a FileStream object 3. Use the FileStream’s open() or openAsync() method 4. If you’re using the asynchronous openAsync() method, you need to set up event listeners for the FileStream 5. Add the code that reads and writes the data you need 6. Call the FileStream’s close() method when you’re done with the file
What You Need to Know About Using FileStream
1. FileMode The open() and openAsync() methods of FileStream both take a fileMode parameter, which controls:
- Whether the file can be read
- Whether the file can be written
- Whether data is always appended to the end of the file (when writing)
- What happens if the file doesn’t exist (or if its parent doesn’t exist)
The specific values are:
FileMode value
Description
FileMode.READ
Opens the file as read-only.
FileMode.WRITE
Opens the file for writing. If the file doesn’t exist, it is created; if it does exist, all of its existing data is deleted.
FileMode.APPEND
Opens the file in append mode. If the file doesn’t exist, it is created; if it does exist, none of its existing data is overwritten, and all written data starts at the end of the file.
FileMode.UPDATE
Opens the file for reading and writing. If the file doesn’t exist, it is created. This mode is typically used for random read/write access to a file. You can read from any position in the file; when writing, only the existing bytes at the write position are overwritten, and all other bytes are unaffected.
2. position This property determines the position at which the next data read or write operation takes place. Before a read or write operation, set the position property to a valid position in the file, for example: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/site.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.open(myFile, FileMode.UPDATE); myFileStream.position = 8; myFileStream.writeUTFBytes(“hello”); This example writes the UTF-encoded string “hello” at position 8. A newly opened FileStream object has a position value of 0. Before a read operation, the value of position must be at least 0 and less than the total number of bytes in the file. The value of position changes only in the following cases:
- Setting the property directly
- Performing a read operation
- Performing a write operation
When a read/write operation is performed, the value of position immediately increases by the number of bytes read/written, and the next read/write operation starts from the new position: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/test.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.open(myFile, FileMode.UPDATE); myFileStream.position = 4000; trace(myFileStream.position); // 4000 myFileStream.writeBytes(myByteArray, 0, 200); trace(myFileStream.position); // 4200 There is one exception to position: if the file is opened in append mode, the position property does not change with write operations. In append mode, data is always written to the end of the file, regardless of position. When you open a file asynchronously, a write operation hasn’t finished by the time the next line of code runs. What to do about that? No worries — you can call several asynchronous operations in sequence, and the AIR runtime executes them one after another: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/test.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.openAsync(myFile, FileMode.WRITE); myFileStream.writeUTFBytes(“hello”); myFileStream.writeUTFBytes(“world”); myFileStream.addEventListener(Event.CLOSE, closeHandler); myFileStream.close(); trace(“started.”); closeHandler(event:Event):void { trace(“finished.”); } This example outputs: started. finished. You can set the value of position immediately after calling an asynchronous read/write operation, and the next read/write will start from that position instead. For example: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/test.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.openAsync(myFile, FileMode.UPDATE); myFileStream.position = 4000; trace(myFileStream.position); // 4000 myFileStream.writeBytes(myByteArray, 0, 200); myFileStream.position = 300; trace(myFileStream.position); // 300 3. Choose the right read/write operation for your data format Every file on disk is a collection of bytes. In AS, the data in a file can always be described as a ByteArray. For example, the code below reads the file data into a ByteArray called bytes: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/test.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.addEventListener(Event.COMPLETE, completed); myFileStream.openAsync(myFile, FileMode.READ); var bytes:ByteArray = new ByteArray(); function completeHandler(event:Event):void { myFileStream.readBytes(bytes, 0, myFileStream.bytesAvailable); } The code below writes the data from the bytes ByteArray into a file: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/test.txt”); var myFileStream:FileStream = new FileStream(); myFileStream.open(myFile, FileMode.WRITE); myFileStream.writeBytes(bytes, 0, bytes.length); Often we don’t want to deal with the data as a ByteArray; sometimes the file we’re handling has a specific format, for example the data in the file is a string. So the FileStream class also includes read/write methods for data formats other than ByteArray, such as the readMultiByte() method, which reads the file into a string: var myFile:File = File.documentsDirectory.resolvePath(“Mousebomb/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”); } The second parameter of readMultiByte() (in this example, “iso-8859-1”) specifies the text format that ActionScript uses to interpret the data. ActionScript supports the common character set encodings, which are listed at http://livedocs.macromedia.com/flex/2/langref/charset-codes.html The FileStream class also has a readUTFBytes() method, which reads data from the read buffer using the UTF-8 character set. Because UTF-8 is a variable-length encoding, the data at the end of the read buffer isn’t necessarily a complete character, so don’t use the readUTFBytes() method inside a progress event handler (the same applies when reading variable-length character encodings with readMultiByte()); instead, read the complete data set when the FileStream’s complete event fires. Likewise, there are corresponding write operations, writeMultiByte() and writeUTFBytes(), for working with string objects and text files. The readUTF() and writeUTF() methods also read and write text data, but they assume the text data is preceded by a specified text data length, which isn’t commonly used in standard text files. Some UTF-encoded text files begin with a UTF-BOM (Byte Order Mark) character, which, like the encoding format (such as UTF-16 and UTF-32), also declares the byte order. The readObject() and writeObject() methods make it easy to store and retrieve data for complex AS objects; the data is encoded as AMF (ActionScript Message Format), a format private to ActionScript. Programs other than AIR, Flash Player, Flash Media Server, and Flex Data Services have no built-in API for handling this format. There are also other read/write operations, such as readDouble() and writeDouble(); when using them, make sure the file format you’re working with matches. File structures in general tend to be far more complex than text files. An mp3 file, for example, contains a compressed data format that can only be interpreted by an mp3 decompression/decoding algorithm. Other files — images, databases, application archives, and so on — all have different structures, and to manipulate their data with AS you need to understand those structures thoroughly. And that brings this study note, “AIR File Operations,” to an end. All the knowledge points come from: the official documentation. (If anything in this article is incorrect, please point it out.) References: http://livedocs.adobe.com/air/1/devappsflash/help.html?content=dg_part_6_1.html http://livedocs.macromedia.com/flex/2/langref/charset-codes.html http://www.adobe.com/go/learn_air_aslr