【转】flash air中读取本地文件的三种方法

时间:2022-12-28 04:26:48

actionscript中读取本地文件操作有两种代码如下

1.使用File和FileStream两个类,FileStream负责读取数据的所以操作:(同步操作)

var stream:FileStream = new FileStream();
var file:File = new File('E:/test.txt');//绑定一个文件
stream.open(file,FileMode.READ);//读取文件
trace(stream.readMultiByte(stream.bytesAvailable,'utf-8'));
stream.close();

稍微需要注意的一点是我们的File()函数里传的路径字符串,里面全都使用的是正斜杠,如果使用了反斜杠,你就会收到来自程序的错误。

2.仅File类(异步操作)

private var file:File;
public function Tracer()
{
    file =new File('E:/daili.txt');//绑定一个文件
    file.addEventListener(Event.COMPLETE,onComplete);
    file.load();//执行读取操作
}

private function onComplete(event:Event):void
{
    vardata:ByteArray = file.data;
    trace(data.readMultiByte(data.bytesAvailable,'utf-8'));
}

3.使用File和FileStream(异步操作)

var sourceFile:File = File.documentsDirectory.resolvePath("Apollo Test/test.txt");
var stream:FileStream = new FileStream();
stream.addEventListener(Event.COMPLETE, readBytes);
stream.openAsync(sourceFile, FileMode.READ);

function readBytes(e:Event):void {
    varbytes:ByteArray = newByteArray();
    trace("position 0:", stream.position);// 0
    bytes[0] = stream.readByte();
    trace("position 1:", stream.position);// 1
    fileStream.readBytes(bytes, stream.position,4);
    trace("position 2:", stream.position);// 5
    stream.close();
}