AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

Reading a Text File and Using it in Flash


Reading the contents of a text file from a web server is another example of an asynchonous event which requires a callback mechanism to deal with the data once it has been read. No serverside script is needed, but the same LoadVars class shown on the previous page will again be used to initiate the data read, and to handle the data once it has been read from the text file. Parsing of the data into a useable format can either be done with a function assigned to the LoadVars onLoad event handler, if the text file is formatted in variable=value pairs separated by ampersands, or with a function assigned to the LoadVars onData event handler, to access the raw ascii data in the file. In either case, data in the text file should always be utf-8 encoded for correct display within Flash. Most text editing programs (including even basic ones like Notepad) have an option to save a file as utf-8.

Using onData to read text as it appears in the file

To read and display the contents of a text file exactly as they appear in the file, use the onData method of the LoadVars object. A text string (the contents of the file) is passed as a parameter to the LoadVars onData method, which you can then assign to a variable or to a textfield in your movie. To put it straight into a dynamic textfield named mybox_txt, for example:

var lv:LoadVars = new LoadVars();

lv.onData = function(thetext:String) {
	mybox_txt.text = thetext;
}

lv.load("thetextfile.txt");  
  

The text may be assigned to a plain dynamic textfield or to an html-formatted one (in which case use mybox_txt.htmlText = thetext instead of the above), with links included in the file (eg, in the middle of my text <font color="#00CCCC"><a href="somelink.com" target="_blank">there is a link</a></font> which opens a new window), as Spencer Bowden has done on the News and About pages for sub-ID, with spacing in the text file providing the diagonal formatting of the left edge. He also proved to me (I love teaching) that you can include html comments (<!-- comments //-->) in the file to give instructions to the person who maintains the file and they will not be displayed in the movie.

onLoad to read formatted data

As we saw on the LoadVars page, data that will be read by a LoadVars onLoad handler must be formatted in variable=value pairs, separated by and preferable also surrounded by ampersands. To make the file more readable, each line can have its own ampersands at the beginning and end -- it doesn't hurt to have extra dummy ampersands in the file. Eg, data for a pie chart showing cookie sales could be passed as individual values (in piechartdata1.txt), like:

  &count0=274&
  &count1=52&
  &count2=216&
  &count3=170&
  &count4=123&
  &color0=0066cc&  
  &color1=999900&  
  &color2=660099&  
  &color3=cc0099&  
  &color4=339900&  
  &category0=chocolate chip&
  &category1=macademia nut&
  &category2=sugar wafers&
  &category3=oatmeal raisin&
  &category4=molasses crinkles&

where each variable name has a numeric suffix to distinguish it from other variables of the same name. The values passed from a text file to Flash are always passed as data of type string, and so must be converted to numeric data if needed within the Flash movie. To read the above into an array of objects with count, color and category properties of the appropriate type (number, number, string, respectively) this onLoad routine could be used:

var lv:LoadVars = new LoadVars();
var cookieInfo:Array = [];

lv.onLoad = function(success:Boolean):Void {
   if (success) {
      var i:Number = 0;
   
      // repeat until all values have been read in
      // remember that this.count5 can also be expressed as this["count"+5]
      while (this["count"+i] != undefined) {
      
         cookieInfo.push({
   					
            // convert string to Number
            count:Number(this["count"+i]),
   			
            // convert hex color as string to Number
            color:parseInt(this["color"+i], 16),
   			
            // no conversion needed for category
            category:this["category"+i]
   		 
         });
         i++;
      }
      displayChart();
   } else {
      trace('The cookie information file could not be read');
   }
}

function displayChart() {
   // code here to display the chart, using cookieInfo
}

lv.load("textfiles/piechartdata1.txt");

Notice that the call to displayChart cannot be put on the line immediately after lv.load because data from the text file will not have been read that quickly from the server. Instead, anything that is to be done after the data has been read must be put inside the onLoad routine, including, in this case, the call to display the chart.

Another formatting possibility

Data in the text file doesn't have to be in the format shown above. Just to show another alternative, the text file (piechartdata2.txt) could look like this:

&countValues=274,52,216,170,123&
&colorValues=0066cc,999900,660099,cc0099,339900&
&categoryValues=chocolate chip,macademia nut,sugar wafers,oatmeal raisin,molasses crinkles&

It all depends on what format is easiest for you, or your client, to read and update. Note that updating has to be done by modifying the text file and uploading it (via FTP or another upload mechanism), or by running a serverside script to modify the file; there is no way to write to a text file on a web server directly from Flash. There is also no way to read or write a text file on the user's own PC/Mac from Flash, unless the movie is published within one of the wrapper programs that have been written to allow local file access (SWF Studio, Zinc, Screenweaver, etc).

Ok, back to the format above. Having written the file with comma-separated values, we can use the split method of the String class (look it up in the Flash help file) to create an array from each comma-separated string, and then put that data into the same array-of-objects format as the example above:

var lv:LoadVars = new LoadVars();
var cookieInfo:Array = [];

lv.onLoad = function(success:Boolean):Void {
   if (success) {
      // make arrays out of each of the passed strings
      var count:Array = this.count.split(",");
      var color:Array = this.color.split(",");
      var category:Array = this.category.split(",");
		
      // make one array to hold all the information: one entry for each cookie type
      for (var i:Number=0; i < count.length; i++) {
         cookieInfo.push({
						
            // convert string to Number
            count:Number(count[i]),
			
            // convert hex color as string to Number
            color:parseInt(color[i], 16),
	
            // no conversion needed for category
            category:category[i]
         });
      }
      displayChart();
   } else {
      trace('The cookie information file could not be read');
   }
}

function displayChart() {
   // code here to display the chart, using cookieInfo
}

lv.load("textfiles/piechartdata2.txt");   
   

The pie chart sample shows how to use the drawing API and the cookie sales file to display an interactive, dynamically generated pie chart.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads