集册 Java实例教程 FileVisitor以打印给定目录上具有给定扩展名的文件数。

FileVisitor以打印给定目录上具有给定扩展名的文件数。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

401
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 
展开阅读全文