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;
}
}
开发者_Python百科
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!!!
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...
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
}
精彩评论