If you have ever used a shell script, you have most likely used pattern matching to locate files. In fact, you have probably used it extensively. If you haven't used it, pattern matching uses special characters to create a pattern and then file names can be compared against that pattern. For example, in most shell scripts, the asterisk, *, matches any number of characters. For example, the following command lists all the files in the current directory that end in .html:
The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher. You can retrieve a file system's PathMatcher by using the getPathMatcher(String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:
Glob syntax is easy to use and flexible but, if you prefer, you can also use regular expressions, or regex, syntax. For further information about regex, see theRegular Expressions lesson. Some file system implementations might support other syntaxes. If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class. The examples in this page use glob syntax.
Once you have created your PathMatcher instance, you are ready to match files against it. The PathMatcher interface has a single method, matches, that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:
Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.
The Find example does precisely that. Find is similar to the UNIX find utility, but has pared down functionally. You can extend this example to include other functionality. For example, the find utility supports the -prune flag to exclude an entire subtree from the search. You could implement that functionality by returning SKIP_SUBTREE in the preVisitDirectory method. To implement the -L option, which follows symbolic links, you could use the four-argument walkFileTreemethod and pass in the FOLLOW_LINKS enum (but make sure that you test for circular links in the visitFile method).
To run the Find application, use the following format:
The pattern is placed inside quotation marks so any wildcards are not interpreted by the shell. For example:
Here is the source code for the Find example:
* Stackoverflow - How do I use directory globbing in JDK7