Text Files

In this example we will read a file that contains a list of names and store it into a TextArea component.
TextArea

Name the TextArea names and make sure that both scroll bars are on Auto.ScrollBars

There is nothing else in the movie except the ActionScript: TextArea

1
2
3
4
5
6
7
8
9
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.text = loader.data; 
}
CODE

Download the file.

When you run the program you will see the names in the text area. 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: Reading a list of links for a combo box