Reputation: 109
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
Upvotes: 0
Views: 1488
Reputation: 15684
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();
Upvotes: 5