Java Stream How to - Filter each line in text file and count








Question

We would like to know how to filter each line in text file and count.

Answer

// www  .j a v  a 2s  .  co  m
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  public static void main(String[] args) throws Exception{
    Path start = Paths.get("c:/Java_Dev/run.bat");
    int maxDepth = 5;
    long fileCount =
        Files
            .walk(start, maxDepth)
            .filter(path -> String.valueOf(path).endsWith("xls"))
            .count();
    System.out.format("XLS files found: %s", fileCount);
  }
}

The code above generates the following result.