Marsh
Marsh

Reputation: 8125

AS3 - How do I import variables from a text-based file?

I couldn't find a good, clear question and answer for this in StackExchange, so I'll pose this as clearly as I can and hopefully get a clear, concise answer.

Suppose I have a .txt* file with variables for a bunch of objects of one type that I was to load into an ActionScript 3 program. I can use an import statement such as:

[Embed(source="test.txt",mimeType="application/octet-stream")]
private var testFile:Class;

for some of the places where I need to do this, but I also need to know how it's different for files chosen by the user from their local hard drive.

In code, how can I convert this file, testFile:Class into an array, result:Array, of strings?

*: If you have a solution using .xml or another format, please also include a sample of what the file's contents would look like and how you would get them into variables within AS3

Edit: Below is a quick example file I threw together, test.txt:

testing
1
2
3
4
5
testing
6
7
8
9
10

And the code I currently have to try to import it as a string (which I can then use string.split("\n") to convert to an array)...which is producing a null string rather than the above:

var fileContent:String = new textFile() as String;
trace(fileContent); // Trace comes back with "null" and 
         // the next line crashes my program for a null reference.
var result:Array = fileContent.split('\n');

Upvotes: 3

Views: 879

Answers (1)

taskinoor
taskinoor

Reputation: 46027

If you create an instance of testFile then that will be a string variable. Then you can parse the string in any way you want. For example the content of file:

line 1
line 2
line 3

And result array should be: ['line 1', 'line 2', 'line 3']

Then do this:

var fileContent:String = new testFile();
var result:Array = fileContent.split('\n') as String;

Upvotes: 2

Related Questions