import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FileCount {
public FileCount() {
/*
sample path
$ tree
.
├── dir1
│ ├── dir1-1
│ │ └── test.txt
│ ├── dir1-2
│ │ └── test.txt
│ ├── tes.txt
│ └── test.html
└── dir2
└── test.html
*/
System.out.println(countFile(Paths.get("To sample path"), "txt"));
}
public long countFile(Path path, final String extension) {
try (Stream<Path> stream = Files.walk(path)) {
return stream
.filter(entry ->
entry.getFileName().toString().endsWith(String.format(".%s", extension)))
.count();
} catch (IOException e) {
e.printStackTrace();
}
return 0L;
}
public static void main(String args[]) {
new FileCount();
}
}