3

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');
Mar
  • 7,765
  • 9
  • 48
  • 82

1 Answers1

2

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;
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
taskinoor
  • 45,586
  • 12
  • 116
  • 142
  • I tried this and I'm getting a null reference for `fileContent` after the first line. – Mar Nov 12 '11 at 06:51
  • What is the content of the file? Please post your actual code. – taskinoor Nov 12 '11 at 07:33
  • Remove `as String`. The code should be `var fileContent:String = new testFile();`. My mistake. – taskinoor Nov 12 '11 at 08:25
  • Works like magic without the `as String` bit. Thanks! Points for you! PS if anyone has answers that work for `.xml` or other methods, please still post your answer; I like to upvote. – Mar Nov 12 '11 at 08:31
  • @wvxvw, thanks for the ByteArray explanation. I missed that thing. – taskinoor Nov 12 '11 at 18:04