遍历目录java.nio.file.DirectoryStream接口

    1. public class WalkDirDemo {
    2. public static void main(String[] args) {
    3. Path dir = Paths.get("D:/java/ebook/");
    4. //返回经过过滤的DirectoryStream,其中包含.wmv结尾的文件
    5. try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.wmv")) {
    6. for (Path path : stream) {
    7. System.out.println(path.getFileName());
    8. }
    9. } catch (IOException e) {
    10. System.out.println(e.getMessage());
    11. }
    12. }
    13. }
    1. 遍历整个目录树
    public class WalkDirDemo {
        public static void main(String[] args)throws IOException {
            Path path = Paths.get("D:/work/zk/opensource/javase/ThinkingInJava");
    
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if(file.toString().endsWith(".java")){
                        System.out.println(file.getFileName());
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }