Flash ActionScript 3:从文件中读取文本

时间:2014-10-20 17:09:30

标签: actionscript-3 file flash save

我的问题是:我想用Flash CS5.5从文本文件(命名为" myText.txt")加载数据。它包含一些行,我想将这些行存储在一个数组中。这就是我现在所得到的:

var myLoader:URLLoader = new URLLoader(new URLRequest("myText.txt");
var myArray:Array = new Array();

myLoader.addEventListener(Event.COMPLETE, loadComplete(myArray));

function loadComplete(myArray:Array):Function {
    return function(e:Event):void {
        myArray = myLoader.data.split("\n");

        for(var i:int = 0; i < myArray.length; ++i){
            trace(myArray[i]);                         // To check if it works at this point
        }
    }
}

for(var i:int = 0; i < myArray.length; ++i){
    trace(myArray[i]);                                 // To check if it gets modified
}

事实是第一部分有效,它加载文本文件并存储在myArray中,并跟踪它;但它只存储在本地版本的myArray中,它不会修改引用,因此函数外部的for不会跟踪任何内容。

我曾经读过,数组是通过flash引用传递的,所以我不明白为什么它不起作用。

我很感激帮助。


修改

现在的事情是,这只是一个测试文件,我希望这个代码在一个我会经常使用的函数中。理想的情况是在名为&#34; Utils&#34;的AS类文件中使用静态函数,以及其他有用的函数。 &#34; Utils.as&#34;的代码文件是这样的:

package Include {

    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.events.Event;

    public class Utils {

        public function Utils() {
        }

        public static function fileToArray(path:String):Array {
            var linesArray = new Array();

            // Code to load the file stored in 'path' (the 'path' String
            // also has the name of the file in it), split by '\n' and store every line
            // in the 'linesArray' Array.
            // Example: path = "file:////Users/PauTorrents/Desktop/program/text.txt"

            return linesArray;
        }

        // other functions

    }

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这里需要解决一些问题。

首先,你的for循环将始终在加载完成之前运行,因此它永远不会跟踪任何内容。当URLoader加载时,AS3不会锁定线程,因此它将继续在等待加载文件时块中的其余代码。

其次,作为你的加载完成处理程序的结果,返回一个年度函数真是太丑了。

我将如何做到这一点:

var myLoader:URLLoader = new URLLoader(new URLRequest("myText.txt");
var myArray:Array = new Array();

myLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);

function loadComplete(e:Event):void{
    myArray = myLoader.data.split("\n");

    for(var i:int = 0; i < myArray.length; ++i){
        trace(myArray[i]);                         // To check if it works at this point
    }

    //now move on with the rest of your program/code
}