FileVisitor在给定目录上打印具有给定扩展名的文件数。
import java.io.IOException; import java.nio.file.*; /** nowjava.com - 时代Java 提供 **/ import java.nio.file.attribute.BasicFileAttributes; /** * FileVisitor example which will print the * number of files with a given extension on a given directory. */ public class FileVisitorExample { public static void main(String[] args) throws IOException { MyFileChecker mfc = new MyFileChecker(); Files.walkFileTree(Paths.get("/home/macluq/tmp"), mfc); System.out.println(mfc.getCount()); } } /*来自 时代Java公众号*/ class MyFileChecker extends SimpleFileVisitor<Path> { private final PathMatcher matcher; private static int count; public MyFileChecker(){ matcher = FileSystems.getDefault().getPathMatcher("glob:*.java"); } void check(Path p){ Path name = p.getFileName(); if(name != null && matcher.matches(name)){ count++; } } public