List files matching a naming pattern in Java

This tutorial shows how to recursively list files matching a naming pattern in Java.

To be able to list the files, you should be able to walk the file tree. JDK 7 provides a FileVisitor interface to walk a file tree. The FileVisitor type is given callbacks at key points in the traversal process. The FileVisitor interface defines the following four methods corresponding to the situation in the traversal:

  • preVisitDirectory – Invoked before a directory’s entries are visited.
  • postVisitDirectory – Invoked after all the entries in a directory are visited. If any errors are encountered, the specific exception is passed to the method.
  • visitFile – Invoked on the file being visited. The file’s BasicFileAttributes is passed to the method
  • visitFileFailed – Invoked when the file cannot be accessed. The specific exception is passed to the method. You can choose whether to throw the exception, print it to the console or a log file, and so on.

One needs to implement the FileVisitor interface and implement all the callback methods. The tree traversal logic is implemented by Files.walkFileTree which takes a FileVisitor type as an input and calls the appropriate FileVisitor interface methods during the traversal.

JDK also provides a default implementation of the FileVisitor interface in SimpleFileVisitor class. Instead of implementing all the FileVisitor methods you can as well extend the SimpleFileVisitor class and override only the methods you are interested in.

For the sake of this tutorial we will extend the SimpleFileVisitor class and implement a simple utility class FileFinder which accepts a wildcard naming pattern and records the all the files that match the pattern during the file tree traversal.

FileFinder Class

Usage

The usage is pretty simple. First, we create an instance of the FileFinder class by passing in the naming pattern. Then, we pass the instance to Files.walkFileTree that give callbacks to our FileFinder instance as it walks the file tree. Our FileFinder instance matches the pattern with every file and directory path that is encountered and records those that match. Files.walkFileTree returns once the traversal is complete. Then you can call getMatchedPaths() on the FileFinder instance that returns a collection of all the paths matching the input naming pattern.

Sample Output

 


 

Leave a Reply

avatar
300
  Subscribe  
Notify of