FileStream 完整操作未触发 AS3

问题描述 投票:0回答:1

当我运行此代码时,文件已成功写入,但没有任何事件触发(或者进程发生得太快以至于它们没有出现)。任何帮助将不胜感激。

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


var myFile:File = File.documentsDirectory.resolvePath("AIR Test/test.txt"); 
var myFileStream:FileStream = new FileStream(); 
myFileStream.addEventListener(Event.COMPLETE, completeHandler); 
myFileStream.addEventListener(ProgressEvent.PROGRESS, progressHandler); 
myFileStream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler); 
myFileStream.openAsync(myFile, FileMode.WRITE); 
myFileStream.writeUTFBytes("Hello world");
 
function completeHandler(event:Event):void { 
    // ... 
    trace("Complete")
} 
 
function progressHandler(event:ProgressEvent):void { 
    // ... 
    trace("Progress")
} 
 
function errorHandler(event:IOErrorEvent):void { 
    // ... 
    trace("Error")
} 
actionscript-3 air filestream
1个回答
0
投票

您将错误的事件设置为您想要执行的操作。
使用

Event.COMPLETE
代替
Event.CLOSE
来表示该过程已结束。不要忘记添加
myFileStream.close()
来实际触发事件。
使用
ProgressEvent.PROGRESS
代替
OutputProgressEvent.OUTPUT_PROGRESS
显示进度。您可以从
myFileStream.close()
事件调用
OUTPUT_PROGRESS
,在该过程分别 100% 后,所有字节均已写入 (
event.bytesPending == 0
)。

工作示例:

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.OutputProgressEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileReference;

var myFile: File = File.documentsDirectory.resolvePath("AIR Test/test.txt");

var myFileStream: FileStream = new FileStream();
myFileStream.openAsync(myFile, FileMode.WRITE);
myFileStream.addEventListener(Event.CLOSE, completeHandler);
myFileStream.addEventListener(OutputProgressEvent.OUTPUT_PROGRESS, progressHandler);
myFileStream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
myFileStream.writeUTFBytes("Hello world");

function completeHandler(event: Event): void {
    // ...
    trace("Complete");
}

function progressHandler(event: OutputProgressEvent): void {
    // ...
    var progressRatio: Number = (1 - (event.bytesPending / event.bytesTotal));
    trace(progressRatio);
    trace("Progress");

    if (event.bytesPending == 0) {
        //All bytes have been written to the file. Close the FileStream to trigger Event.CLOSE
        event.target.close();
    }

}

function errorHandler(event: IOErrorEvent): void {
    // ...
    trace("Error");
}
© www.soinside.com 2019 - 2024. All rights reserved.