Course contentsShow
← Java
Lesson 2092 of 2,87041. NIO.2 and the Path APIFree lesson

Practical Use Cases: Search, Delete, Copy

Implementing common operations like recursive search, directory deletion, and tree copying with file visitors.

Practical Use Cases: Search, Delete, Copy

What you'll learn: How to combine file visitors with real-world tasks like recursive searching, safe directory deletion, and complete tree copying.

Putting File Visitors to Work

Now that you understand FileVisitor and walkFileTree, let's see how they solve common file system challenges. These operations would be tedious with loops but become elegant with visitors.

Recursive Search

Extend SimpleFileVisitor and override visitFile to check each file against your criteria. Use FileVisitResult to skip subtrees that don't match:

class SearchVisitor extends SimpleFileVisitor<Path> {
    private String targetName;
    
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        if (file.getFileName().toString().equals(targetName)) {
            System.out.println("Found: " + file);
        }
        return FileVisitResult.CONTINUE;
    }
}

Files.walkFileTree(startPath, new SearchVisitor("report.txt"));

Safe Directory Deletion

Deleting a directory requires removing contents first. Visit files in post-order by overriding postVisitDirectory:

class DeleteVisitor extends SimpleFileVisitor<Path> {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.delete(file);
        return FileVisitResult.CONTINUE;
    }
    
    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        Files.delete(dir);  // Delete after contents removed
        return FileVisitResult.CONTINUE;
    }
}

Tree Copying

Copy directories by creating them in preVisitDirectory and copying files in visitFile:

Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        Path targetDir = target.resolve(source.relativize(dir));
        Files.createDirectories(targetDir);
        return FileVisitResult.CONTINUE;
    }
    
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.copy(file, target.resolve(source.relativize(file)));
        return FileVisitResult.CONTINUE;
    }
});

Key Takeaway: File visitors turn complex recursive operations into clean, maintainable code by separating traversal logic from action logic—perfect for search, deletion, and copying tasks.