Working with txt file on as3

2019-09-05 15:19发布

I'm not very used to as3. I want to convert some data from txt file to actual as3 object.

  1. How do I load text at "/data/file.txt"
  2. How do I find words in the text? For example: I want to find 'frame' and retrieve every symbol serie (separated with space) and add it into an array/table.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-05 15:44

1.

It depends. If the file's on the client machine, you can only load it if you're using AIR (Flash Player, which runs out of the browser, does not support this). Use FileStream.readUTFBytes(), like this:

try
{
    var file:File = new File();
    file.nativePath = "the file's path, including the file name";

    if (file.exists)
    {
        var fs:FileStream = new FileStream();
        try
        {
            fs.open(file, FileMode.READ);
            var strFileContents:String = fs.readUTFBytes(fs.bytesAvailable);
        }
        catch (eInner:Error)
        {
            Alert.show(eInner.message);
        }
        finally
        {
            fs.close();
        }
    }
}
catch (eOuter:Error)
{
    Alert.show(eOuter.message);
}

A couple of notes about this: If I'm not mistaken, at least unless you find some sort of special trick to do this, the File's nativePath property needs to be set to either an absolute path or, if it is a relative path, it needs to be within the same directory as the program (it can be in a subdirectory). This is probably a security thing Adobe intentionally implemented. Also setting the nativePath (either explicitly or through the constructor) can raise an error, so the outer try...catch block is important too.

If you're loading the file off a server through a URL, you can use either Flash Player or AIR. Just use a URLLoader instead:

private var m_ldr:URLLoader = new URLLoader();

private function func()
{
    try
    {
        m_ldr.dataFormat = URLLoaderDataFormat.TEXT; // default
        m_ldr.addEventListener(Event.COMPLETE, ldrDone);
        m_ldr.load(new URLRequest("URL of the file"));
    }
    catch (e:Error)
    {
    Alert.show(e.message);
    }
}

private function ldrDone(pEvent:Event):void
{
    var strContents:String = m_ldr.data;
}

2.

I'm not sure I follow what you're wanting to do with the text, but you can split a String into an array. If you want to find the word "frame", and if you care about case in this instance, you can do something like the following:

var strString:String = "Frame: The first definition at dictionary.com for the" +
        "word frame is \"a border or case for enclosing a picture, mirror, " +
        "etc.\".  A related word is framed, and frame can also be used as a verb."
        + " ... frame";

// notice how I specifically avoided wrapping double-quotes around the word
// "frame".  That makes this easier, because now we just have to split on
// whitespace:

var arry:Array = strString.split(/\s/); // splits on all whitespace
for (var i:int = 0; i < arry.length; i++)
{
    if (arry[i] == "frame")
    {
        trace("Element " + i + " is the word \"frame\"." + (i < arry.length - 1 ?
                "  The next word is \"" + arry[i + 1] + "." : "\""));
    }
}

// outputs:
// Element 10 is the word "frame".  The next word is "is".
// Element 27 is the word "frame".  The next word is "can".
// Element 36 is the word "frame".
查看更多
Rolldiameter
3楼-- · 2019-09-05 15:56

For loading text file you will need URLLoader, for searching, String methods

Working example:

package {

    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class StackOverflow extends Sprite {

        public function StackOverflow() {
            addEventListener(Event.ADDED_TO_STAGE, onAdded);
        }

        private function onAdded(e:Event):void {
            removeEventListener(Event.ADDED_TO_STAGE, onAdded);

            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            loadFile("./data/file.txt");
        }

        private function setup(fileContent:String):void {
            var searchWord:String = "commodo";
            var position:int = fileContent.indexOf(searchWord);
            var result:String = fileContent.substr(position + searchWord.length);
            var resultAsArray:Array = result.split(" ");
        }

        private function loadFile(path:String):void {
            var loader:URLLoader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, onComplete);
            loader.load(new URLRequest(path));
        }

        private function onComplete(e:Event):void {
            var content:String = URLLoader(e.currentTarget).data;
            setup(content);
        }
    }
}

Content of file is:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Result will be all text from the word commodo

查看更多
登录 后发表回答