views:

25

answers:

2

Hi to all, I need to read a file, which has an "n" number of lines, I need to know when reading the end of each line, so I can store the line in an array, ok so far I have

while(stream.position < stream.bytesAvailable)
    {
        char = stream.readUTFBytes(1);
        if(char == "\n")
        {
            array.push(line);
            line = "";
        }
        else
        {
            line += char;
        }
    }

my question is, always the end of line will be "\n"?? how can I be sure if is not an other character like \r??, there is an other character for end of line??, thanks for any help!!!

A: 

Since you're reading the whole stream anyway, putting it into memory, why not just load it into a string and then split the string into lines at that point. You can test the string first for \n or \r or the combination of \r\n (which you should test for first).

Example, where myFileString is what you've read in:

var lineEnding = ''; // String var for storing line ending char or char combo
var lines = []; // Array var for storing the lines of the string

if (myFileString.match('\r\n') {
  lineEnding = '\r\n';
} else if (myFileString.match('\r') {
  lineEnding = '\r';
} else if (myFileString.match('\n') {
  lineEnding = '\n';
}

if (lineEnding != '') {
  lines = myFileString.split(lineEnding); // here are your lines
} else {
  lines[0] = myFileString; // it's one line
}
Robusto
+2  A: 

How about something like this:

var lines:Array = stream.readUTF().split('\r\n').join('\n').split('\n');

It reads the entire string from the file and then first splits on windows line endings, replacing them with unix line endings. It then splits again on unix line endings. The result should be an array containing all of the lines...

vitch
Your solution is more elegant than mine (which I made verbose to illustrate the concepts involved more simply), so I gave it +1. Note that it will not find line endings from pre-OS X Macs, which are \r. Just noting that yours could be rewritten to include that if that were a problem.
Robusto