user1845928
user1845928

Reputation: 51

Count number of lines in text skipping the empty ones

I need help with this. Can you tell me how to calculate the number of lines in the input.txt without counting the empty space lines?

So far, I tried:

    BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
    int lines = 0;
    while (reader.readLine() != null)
    lines++;

So, this code is able to count the number of lines, but with the empty lines! I know that there are characters /n which illustrates the new line but I do not know how to integrate it in the solution.

I also tried to calculate number of lines, number of empty lines and subtract them, but I wasn't successful.

Upvotes: 3

Views: 3392

Answers (4)

Marcos Gomes
Marcos Gomes

Reputation: 41

Clean and fast.

try (BufferedReader reader = new BufferedReader("Your inputStream or FileReader")) {
            nbLignes = (int) reader.lines().filter(line -> !line.isEmpty()).count();
        }

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500095

You just need to remember the line you're looking at, and check it before counting:

int lines = 0;
String line;
while ((line = reader.readLine()) != null) {
    if (!line.isEmpty()) {
        lines++;
    }
}

Note that you should be closing your reader too - either in an explicit finally statement, or using a try-with-resources statement in Java 7. I'd advise not using FileReader, too - it always uses the platform default encoding, which isn't a good idea, IMO. Use FileInputStream with an InputStreamReader, and state the encoding explicitly.

You might also want to skip lines which consist entirely of whitespace, but that's an easy change to make to the if (!line.isEmpty()) condition. For example, you could use:

if (!line.trim().isEmpty())

instead... although it would be cleaner to find a helper method which just detected whether a string only consisted of whitespace rather than constructing a new string. A regex could do this, for example.

Upvotes: 3

Nir Alfasi
Nir Alfasi

Reputation: 53525

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
int lines = 0;
String line;
while ((line = reader.readLine()) != null){
    if(!"".equals(line.trim())){
        lines++;
    }
}

Upvotes: 5

rgettman
rgettman

Reputation: 178253

BufferedReader's readLine() method only returns null when the end of the stream has been reached. To not count empty lines, test if the line exists and if it's empty then don't count it.

Quoting the linked Javadocs above:

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Upvotes: 2

Related Questions