Jun
09
2008

Loading an external text file with ActionScript 3

To load a text file with ActionScript, you only need few lines of code. I'm gonna present both, a short way and a valid way of doing it.

In order to load an external text file, you need to use URLLoader, which is designed for loading text files, XMLs or binary data. We can't use a Loader class, which was designed to import only Flash supported files like swf, jpg, png or gif. As usual with any kind of loading classes, we also need to use URLRequest which identifies the location of the file and initiates download. We are going to listen for Event.COMPLETE to know when Flash finishes loading our text file. Also, if file is bigger we can listen for ProgressEvent to get the number of bytes loaded and create the preloader (for more info about preloading read article: Two ways of preloading in ActionScript 3).

Below is the code to quickly import a text file and trace it. I created a text file called mytextfile.txt and placed it in the same folder where the swf is.

1
2
3
4
5
6
7
var  myLoader:URLLoader  =  new  URLLoader(new  URLRequest("mytextfile.txt"));
myLoader.addEventListener(Event.COMPLETE, loadComplete);

function loadComplete(e:Event):void
{
trace(myLoader.data);
}

In the output box, you should see printed content of your text file. Pretty easy, isn't it?

OK, as promised, now the long way, sometimes called also "the proper way". First, some sources say that you should actually define an event listener before loading a text file, as in some cases, text file might load first before Flash actually starts to listen for a Complete event, so you won't know if the file was loaded or not. I don't know if that's true, anyway, Adobe in theirs examples also add listeners first...

Also it's advisable to handle any errors thrown due to problems with loading the files. In order to do that, you need to first use try...catch block to catch the errors and then add an event listener to get information about the errors. Without a listener, Flash would print the error to the output window, but since you also want to get information about error when using swf from the website, you should print it to the text field (output is only available when testing in Flash Application). Note that you can't just add listener to listen for error events without try...catch block as there would be nothing to listen for - no event will be thrown. You won't even know if the file was successfully loaded or not, maybe only from the blank text field...

Anyway, this is how I would do that in a proper way. In my project, I'm trying to load the same file - mytextfile.txt that is in the same folder and print its content to the TextField. Next, to test errors catching, I going to remove that text file and check if Flash catches the error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package
{
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.text.TextField;
import flash.events.Event;
import flash.events.IOErrorEvent;

public class TxtLoader extends MovieClip
{
var myTextField:TextField;

var myLoader:URLLoader;
var filePath:String;
var myReq:URLRequest;

public function TxtLoader():void
{
trace("TxtLoader: Hello World");

//create a Text Field, make it to be multiline
//and set a word wrap as text from the text file will be long
//also set the high and width to be same as stage size
myTextField = new TextField();
myTextField.multiline = true;
myTextField.wordWrap = true;
myTextField.width = stage.stageWidth;
myTextField.height = stage.stageHeight;
addChild(myTextField);

//declare path and file name
filePath = "mytextfile.txt";
//create URLRequest to access the file
myReq = new URLRequest(filePath);
//create URLLoader to load the file
myLoader = new URLLoader();
//add event listener to run fileLoaded function when loading is complete
myLoader.addEventListener(Event.COMPLETE, fileLoaded);
//add event listener to listen for any error thrown during loading process
myLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
//block to catch errors when performing loading
try
{
//start loading a file with our URLLoader instance
myLoader.load(myReq);
}
catch(error:Error)
{
trace("Just catched the error :(");
}
}

//loading complere so print content of a text file to our Text Field
public function fileLoaded(e:Event):void
{
//content is accessed using data property
myTextField.text = myLoader.data;
}

//if any error was thrown, event was also dispatched and now you can print
//the error description to the text field.
public function ioErrorHandler(e:IOErrorEvent):void
{
myTextField.text = "There was a problem loading a "+filePath+" file: "+e;
}
}
}

If everything is ok and your text file is in correct place you should see its content printed in the TextField.

If you remove the text file or change its name and test your project again, you should see this message in the Text Field:

There was a problem loading a mytextfile.txt file: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: file:///D|/eu/sierakowski/samples/txtloader/mytextfile.txt"]

The other types of error that you may encounter are the security errors; this would be the case when your text file is not in the same place but on different web server and domain... But this is a subject for another article :)

If your text file is huge (you try to load a whole book :) or you load binary data), you may want to use preloader. If so, please read this article: Two ways of preloading in ActionScript 3.

 

Comments 

 
0 #1 TheBird 2010-03-10 21:39
We better do that in a valid way, otherwise Steve Jobs will never allow Flash to his bloody toys, iPads...
Quote
 

AS3 Tips

Follow me on Twitter