0

At the moment to count the number of lines from a text file I'm using :

File f = new File("lorem.txt");
if(f.exists()){
        try {
            BufferedReader bf = new BufferedReader(new FileReader(f));

            while((s = bf.readLine())!=null) {
                if(s.length() > 0) {
                    nbLinesTotal++;
                }
            }
            bf.close();
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
}

But I discovered this in java 8 :

long count = Files.lines(Paths.get("lorem.txt")).count();

which is way faster and better than my loop. But it doesn't ignore blank lines. So, How can I ignore blank lines with this way to do ?

Thanks

Srithovic
  • 109
  • 1
  • 2
  • 9

1 Answers1

5

Files.lines returns a Stream<String>. You can therefore use the same filtering operations as you can on any other stream:

long count = Files.lines(Paths.get("lorem.txt")).filter(line -> line.length() > 0).count();
Joe C
  • 15,324
  • 8
  • 38
  • 50