BufferedReader does not return null on last line

The last line is empty, but it doesn't return null

. The code looks like this

When debugging with Eclipse

I have seen line= ""

in debug mode, how can I prevent this from happening?

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
   // process the line.
}
br.close();

      

+3


source to share


4 answers


You are not preventing this, the empty string is a string, so it will be returned as is.

What you can do is check if the string 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();

      

+6


source


The BufferedReader.readLine () method returns null when it reaches the end of the file.



Your program seems to read a line in a file before it gets to the end of the file. The termination condition is that the string is null, the empty string is not null, so it is terminated and not terminated.

+4


source


If the line consists of a line break line

, it will be empty String

but readLine

will not return null. readLine

returns null only after you reach the end of the file.

+2


source


nulll = nothing. "" = empty. If the last line is empty, "expected". The next line must be null.

from there you can check for emptiness (I like the StringUtils isEmpty app) or remove the last file \ n from the file before processing.

+2


source







All Articles