Sunday, July 26, 2009

Load Text From an External Text File using Action Script

There are two ways you can load data from an external text file:
1. You can load the whole text present in the file
2. Or you can format the text so that you can load in parts if you want to.

To Begin create a text file myText.txt or whatever you like and copy and paste the following text in it

&monthNames=January,February,March,April,May,June,July,August,September,October,November,December &dayNames=Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday

"&monthNames" and "&dayNames" are the labels which will help us to acess a part of the data. You can name
them in any way you like such as "&part", "&xxx" or "&whatEverILike". All the parts you would like to access
should have a different label.

Now create a file loadText.fla and save it in the SAME FOLDER as the text file.Create a second layer and name
it "Action". Select the first layer and click on the Text Tool and go to properties panel and set the Text Type
as Dynamic Text and select the Line Type as Multiline then create three text fields.

Select each one at a time and give their instance name in the
Properties Panel as monthnames_txt, daynames_txt and alltext_txt respectively. Create small Satitc Text boxes on top
of each previous text boxes and create labels. At the end of these steps your stage should look somewhat like this.

That done right click on the first frame of the Action layer and select Actions
In the window that opens copy and paste the following script. I think it's sufficiently documented.

//declare two objects of the LoadVars class to load the text file
var text_lv:LoadVars = new LoadVars();
var text1_lv:LoadVars = new LoadVars();

text_lv.load("myText.txt");//load file to display in parts
text1_lv.load("myText.txt");//load file to display the whole text

//display the text in parts
text_lv.onLoad = function (success:Boolean)
if (success)
monthnames_txt.text =text_lv.monthNames;//show text labelled as "&monthnames"
daynames_txt.text =text_lv.dayNames;//show text labelled as "&daynames"
monthnames_txt.text = " Cannot Open File ";//error message

//display the whole text
text1_lv.onData = function (myText:String)
alltext_txt.text = myText;

That's it! Hit Ctrl+Enter to test. If the text is not visible make sure the color of the text fields is not the
same as the background color, also check that you have saved the flash file and the text file in the same folder.

No comments:

Post a Comment