Search code examples
actionscript-3urlloader

I am trying to parse a text file I loaded in Actionscript 3.0, help please


All I can find information on for the URLLoader object in Actionsript 3.0 involves loading XML files, which I don't want to do. I'm trying to load in a .txt file that I want to parse, line by line with each line being delimited by a comma. Anyone know a method of doing this or a place where I can find some information on how to do this? Thanks!


Solution

  • Look at the String's split() methods for start. It splits a string into an array based on a delimiter. In your case you would access each line as an element of the array returned by using split() and the comma character.

    e.g.

    var csvLoader:URLLoader = new URLLoader(new URLRequest('yourFile.csv'));
    csvLoader.addEventListener(Event.COMPLETE, csvLoaded);
    
    function csvLoaded(event:Event):void{
       var lines:Array = String(event.target.data).split(',');
       var linesNum:int = lines.length;
       for(var i:int = 0 ; i < linesNum; i++){
          trace('line ' + i + ': ' + lines[i]);
       }
    }
    

    You can use event.target.data.split(','), I used String to make split()'s origin obvious.

    @dhdean's tutorial is pretty cool, bare in mind that is as2.0, so there are slight differences with loading the file, but parsing strings should be pretty much the same in as2.0/as3.0

    Depending on your comfort level with as3.0 you might want to have a look at csvlib.

    HTH, George