Skip to content

Instantly share code, notes, and snippets.

@ansig
Created November 16, 2014 20:07
Show Gist options
  • Save ansig/b10e7feea6f805ce8b4d to your computer and use it in GitHub Desktop.
Save ansig/b10e7feea6f805ce8b4d to your computer and use it in GitHub Desktop.
Traverse a directory tree with a FileVisitor and print every file that matches a Glob pattern.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
/**
* Traverse a directory and print every file that matches a Glob pattern. In this example, the users home dir is
* searched for .java and .py files.
*/
public class FileFinder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
public FileFinder(String globPattern) {
this.matcher = FileSystems.getDefault().getPathMatcher("glob:" + globPattern);
}
public int getNumMatches() {
return this.numMatches;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
Path name = file.getFileName();
if (name != null && this.matcher.matches(name)) {
this.numMatches++;
System.out.printf("Found: %s%n", file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr) {
Path name = dir.getFileName();
if (name != null && name.toString().startsWith(".")) {
System.out.printf("Skipping hidden dir: %s%n", name);
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException ioe) {
System.out.printf("Could not visit file '%s': %s%n", ioe.getMessage(), file);
return FileVisitResult.CONTINUE;
}
public static void main(String[] args) throws IOException {
Path startingDir = Paths.get(System.getProperty("user.home"));
FileFinder finder = new FileFinder("*.{java,py}");
Files.walkFileTree(startingDir, finder);
System.out.printf("Finder found %d files!", finder.getNumMatches());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment