How can I detect the end of a line in a file ?
Hi folks,
I would like to detect an end-of-line in my .txt file but can't find the right way to do.
My program already detects the last word of the line so what I did is to look at each char of my last word using the "charAt()" method. More precisely, if I'm at position "i" of my word, I check whether the char(i+1) is equal to '\r' or '\n'.
Before that, I did a System.getProperty("line.separator") and it returned "\r\n". So obviously, the char right after the last char of my word should be '\r', no ?
When I'm positioned on the last char of my word and I try to do charAt(i+1), I get a "java.lang.StringIndexOutOfBoundsException".
My question is : how come I can't detect this '\r' with charAt() ? Is there some way to detect it ?
Thanks for your help!
Re: How can I detect the end of a line in a file ?
How are you reading the file? If you're reading it one line at a time, I'd imagine there's a chance that these characters are being stripped automatically. Ditto if you're using the Scanner to get words individually...
If you're trying to read the file one character at a time, I'd imagine what you are doing would work. Do you have any code snippets to share?
Re: How can I detect the end of a line in a file ?
I use readLine() from BufferedReader.
I don't have the code anymore since I used another way, which is the split method from String. It stores the words in an array, and I just pick the last element in the array, since what I want is the last word of the line.
But I still don't know how to stop if you read one char at a time (this is what I was doing)...
Any suggestion ?
Re: How can I detect the end of a line in a file ?
Post your code for how you're reading in the file. It is possible that your method is dropping all EOL strings as many of Java's default readers use EOL to denote a point to stop reading. It is also possible that the data in your .txt file was stored using a "different" standard than the "\r\n" windows uses. In this case, it is probably just a '\n' character.
There is also the probability that there is no EOL character sequence at the end of the file, in which case your program is trying to access data that simply isn't there resulting in the the StringIndexOutOfBoundsException. To prevent this, check to make sure that your not using charAt() outside of the string's length:
Code :
if (index < str.length())
{
// do your charAt() comparison in here
}