Text Files

In this example we will read a file that contains a list of names and store the contents in an array.

There is nothing in the movie except the ActionScript:

1
2
3
4
5
6
7
8
9
10
11
var names: Array;
var file:URLRequest = new URLRequest("http://www.zebra0.com/resources/names.txt");
var loader:URLLoader = new URLLoader(); //a loader for the file
loader.load(file);
// Listen for when the file has finished loading.
loader.addEventListener(Event.COMPLETE, loaderComplete);
function loaderComplete(e:Event):void {
    // The output of the text file is available via the data property of URLLoader.
  names = loader.data.split(/\n/); //split into indiviual lines and store in array names
  trace(names);
}
CODE

When you run the program you will see the names in the output window. This is just slightly different than the first example. Instead of using trace to display loader.data, we split up the data by looking for each new line, \n in the file.

Explanation:

  • 1. We declare an array to hold the names.
  • 2. The URLRequest tells ActionScript where to find the file.
  • 3. and 4. The loader actually reads the files and stores the result in the loaders data.
  • 6. We use a listener to let us know when the files has completely loaded.
  • 9. When the file has finished loading we split the file into individual lines and assign that to the array names.
  • 10. We display the array names using trace.

Once the array has the names we can use it in any way we want.

Challenge: modify the Scrolling messages program by reading the messages from messages.txt.

NEXT: Read names and display in TextArea component