FileVisitor to print the number of files with a given extension on a given directory. - Java File Path IO

Java examples for File Path IO:File Visitor

Description

FileVisitor to print the number of files with a given extension on a given directory.

Demo Code


import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;

/**/* w w w  .  j ava 2s  . com*/
 * 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());
    }
}

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 int getCount(){
        return count;
    }

    public FileVisitResult visitFile(Path p, BasicFileAttributes attr){
        check(p);
        return FileVisitResult.CONTINUE;
    }
}

Related Tutorials