Sunday, November 01, 2009

Flash, AIR, ActionScript: File & FileStream

Cannot write to filesystem at File.applicationDirectory
But yet you can write using File.applicationDirectory.nativePath

To serialise an object of a custom class,
1) use flash.net.registerClassAlias( aliasName:String, classObject:Class)
to register the class before writing or reading
2) implement IExternalizable to your custom class
- readExternal(input:IDataInput):void
- writeExternal(output:IDataOutput):void
- Alternatively, you can use public fields in the custom class. But that is not entirely recommended for real world application.


import flash.filesystem.*;
import flash.net.*;

var a:A = new A();
...
...

function write():void{
registerClassAlias("A", A);
fileStream.open(file, FileMode.UPDATE);
fileStream.writeObject(a);
fileStream.close();
}
function read():void{
fileStream.open(file, FileMode.READ);
var o:A = fileStream.readObject() as A;
o.c();
fileStream.close();
}

/********************
class A
********************/
import flash.utils.*;

public class A implements IExternalizable
{
var b:int = 10;
public function c():void{
trace(b);
}
public function readExternal(input:IDataInput):void
{
b = input.readInt();
}
public function writeExternal(output:IDataOutput):void
{
output.writeInt(b);
}
}

No comments: