Actionscript 3导出到文本文件

时间:2014-11-12 21:16:45

标签: actionscript-3 text air export

只是玩弄Actionscript 3 / AIR,找不到允许导出到同一文件夹中的简单txt文件的体面教程。我有点捏造这段代码,并希望有人可以看一看并指出我出错的地方。

目前收到错误消息 5006:An ActionScript file can not have more than one externally visible definition:file,doSave

package  {

    import flash.events.Event;


    public var file:FileReference = new FileReference();


    public function doSave( event:Event ):void
    {
       var data:ByteArray = new ByteArray();
       data.writeMultiByte ( txtField.text, "test" );
       file.save( data, "MyTextFile.txt" );
    }
}

1 个答案:

答案 0 :(得分:0)

您的错误实际上与保存文件无关。这是因为你的包中缺少类定义(所有代码,vars需要包含在类中)。试试这个:(其中MyFile是.as文件名的占位符)

package  {

    import flash.events.Event;
    import flash.net.FileReference;
    import flash.utils.ByteArray;

    public class MyFile {
        public var file:FileReference;

        public function doSave(text:String):void
        {
            file = new FileReference();
            file.addEventListener(Event.COMPLETE, onSaveComplete, false, 0, true);

            var data:ByteArray = new ByteArray();
            data.writeMultiByte(text, "utf-8" ); //use a proper charset for it to work right
            file.save( data, "MyTextFile.txt" );
        }

        private function onSaveComplete(e:Event):void {
            file = null; //free up the file reference to be garbage collected now that the save is complete
        }
    }
}

然后,您的其他代码应如下所示:

saveButton.addEventListener(MouseEvent.CLICK,saveButtonClick,false,0,true);

function saveButtonClick(e:Event):void {
    var save:MyFile = new MyFile();  
    save.doSave(txtField.text); 
}

如果您想放弃保存为框,让用户选择放置它的位置,只需将文件直接保存在某处而无需用户交互,这将是一种方法:

var file:File = new File("app:/MyTextFile.txt"); //the application directory, which may or may not be allowed write access
var file:File = File.applicationStorageDirectory.resolvePath("MyTextFile.txt"); //use this alternatively which is default profile save location for your application

var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.WRITE);
fileStream.writeMultiByte(data);
fileStream.close();