6.5.  Find a file by using the PathMatcher class

[Note]

The new Java 7 NIO.2 java.nio.file package provides programmatic support for files locating by pattern matching. Each file system implementation provides a PathMatcher interface implementation:

public interface PathMatcher {

    /**
     * Tells if given path matches this matcher's pattern.
     */
    boolean matches(Path path);

}
					

You can retrieve a file system's PathMatcher by using the getPathMatcher(String) method in the FileSystem class.

You can get the path matcher from the file system using this code:

FileSystem fs = FileSystems.getDefault();
PathMatcher matcher = fs.getPathMatcher("glob:" + pattern);
					

The string argument passed to getPathMatcher specifies the syntax flavor and the pattern to be matched. This example specifies glob syntax.

At least two syntaxes are supported (others may be supported by a particular file system implementation):

For both the glob and regex syntaxes, the matching details, such as whether the matching is case sensitive, are implementation-dependent and therefore not specified.

If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class.

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 .txt and .doc and prints those files to standard output:


Path startDir = Paths.get("C:\\home");

String pattern = "*.{txt,doc}";

FileSystem fs = FileSystems.getDefault();
final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern);

FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) {
        Path name = file.getFileName();
        if (matcher.matches(name)) {
            System.out.print(String.format("Found matched file: '%s'.%n", file));
        }
        return FileVisitResult.CONTINUE;
    }
};
Files.walkFileTree(startDir, matcherVisitor);

					

the output could be as follows:

Found matched file: 'C:\home\zaikin\foo\company\readme.txt'.
Found matched file: 'C:\home\zaikin\foo\resume.doc'.
Found matched file: 'C:\home\zaikin\foo\test.txt'.
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide