uthra
uthra

Reputation: 27

while processing a file, break process if there are empty strings in between lines but not when its at the end of the file

While reading files in Java, I should break the process if there are empty lines in between. But this condition should be ignored if the empty lines are at the end of the file.

while ((line = reader.readLine()) != null) {
    if (line == null || line.trim().length() <= 0) {
        log.debug("Terminating on first blank line");// terminate on first blank line
        empty_line = true;                                
        break;
    }
}

The problem with the code above is that it breaks even when the empty lines are at the end of the file which should not happen. How do I do this?

Upvotes: 0

Views: 67

Answers (1)

Stefano Losi
Stefano Losi

Reputation: 729

You must break the process when reading a NOT blank line after having read a blank line.

bool blankLineRead = false;
while ((line = reader.readLine()) != null) {
    //Inside the cicle line is surely not null
    if (line.trim().lenght() <= 0)
        blankLineRead = true;
    else
        if (blankLineRead) {
            log.debug("Terminating on first blank line");// terminate on first blank line
            break;
        }
}

Upvotes: 2

Related Questions