Reputation: 1013
The last line contains nothing , yet it does not return null
. Code is as follows
When debug using Eclipse
, I saw line= ""
in debug mode, how do I prevent this from happening
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
Upvotes: 3
Views: 4063
Reputation: 12843
The BufferedReader.readLine() method returns null when it reaches the end of file.
Your program appears to be reading line in the file before it reaches to the end of the file. The condition for terminating is that line is null, empty string is not null so it loop and dont get terminated.
Upvotes: 4
Reputation: 292
nulll = nothing. "" = empty. If the last line is empty "" is expected. The following line should be null.
from there you can test for emptyness (I like the appache StringUtils isEmpty) or remove last \n from your file prior to processing.
Upvotes: 2
Reputation: 15533
You don't prevent it from happening, an empty line is a line, so it will be returned as is.
What you can do is to check if the line is empty before processing:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
// process the line.
}
}
br.close();
Upvotes: 6
Reputation: 71009
If the line consists of a single line break line
will be empty String
, but readLine
will not return null. readLine
only returns null once you reach the end of the file.
Upvotes: 2