Simple File Visitor in Java

1.5k Views Asked by At

I'm using the simple file visitor for the first time and the documentation seems to be a little less than friendly. Basically I want to visit the directory tree and log the number of folders, the number of total files, and the number of different files like, txt, csv, etc that was visited.

This is my FileVistor.

public class FileVisitor extends SimpleFileVisitor<Path>{


    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        System.out.println("About to scan " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        System.out.println("Scanned " + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {


        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.err.println(exc.getMessage());
        return FileVisitResult.CONTINUE;
    }


}

And this is my calling code.

Scanner scanner = new Scanner(System.in);
    String str = scanner.nextLine();
    Path path = Paths.get(str);
    FileVisitor visitor = new FileVisitor();
    Files.walkFileTree(path, visitor);

Any help appreciated.

0

There are 0 best solutions below