I have a question about a school assignment I need to do it in Java. I need to load data from a file and check for errors in these files.
I read the file with a bufferedReader
which works perfectly until the end of the file: it ignores the last line if that line is empty.
I know how to check for empty lines, but the last line simply doesn't give any result using the readLine()
function of bufferedReader
.
It's important that I know if the last line is empty as it must be. If the empty line doesn't exist, it should give an error.
So long story short, I need a way to tell the difference between the following situations (where CRLF
is the end of the line):
Situation 1 (correct):
line x CRLF
line y CRLF
Situation 2 (wrong):
line x CRLF
line y
Both of these situations will return a null on readline()
after line y.
I am counting the lines of the file on the way, so if I have a line counter (Note: that counter must count that empty line too, all the ones I found did not count them)
The files contain empty lines throughout too, if that should make any difference for the code I need (these lines are properly detected as they should be as the EOF
isn't on these lines)
Note that the program works with or without that last line, it's purely that the assignment tells me to give an error if it's not there.
This would give you the last Line of the file. Why not check if the last line is empty or not ?
There is no empty line in your "situation 1". The
CRLF
belongs to line y and after that, there is nothing (which is whatreadline()
tells you too). It's just that in an editor, thisCRLF
tells the cursor to go one line down, so it looks like a new, empty line there, but in fact that's just an 'optical illusion' caused by the editor interpreting the charactersCR/LF
as a hint to show the cursor in a new line.If you want to determine if the last line has a CRLF you can read from the end.
Have a look at
java.util.Scanner
. You'll be able to iterate usingScanner#hasNextLine()
andScanner#nextLine()
.