Searching file types with PathMatcher

Reading Time: 2 minutes

The PathMatcher class allows us to search any file name or file extension. you can use regex or glob elements to find files. The PathMatcher only seeks the given keyword in the working directory only, It will not search the subdirectories. If you want to seek it in a given path, you should empower it, with the FileVisitor interface. In the below sample snippet, you’ll find an example with the FileVisitor interface.

Sample Usages

glob:*.{java,class} Match path names that end with extension .java or .class
glob:*{java,class} Match path names that end with java or class. They might
not include a dot just before (note the missing dot just
before { ).
glob:*java,class Match path names that end with java,class; for example, Hellojava,
class, and Hello.java,class (java,class doesn’t evaluate
to either java or class).
glob:???.class Match path names that include exactly three characters followed
by .class. For example, it will match abc.class,
ab,.class, and a!b.class. It won’t match abcd.class or
abcde.class.
glob:My[notes,tips,ans].doc Match an exact match of ‘My’ followed by any one character
included within [], followed by .doc. For example, it matches
Mys.doc and My,.doc. It doesn’t match notes.doc,
Mytips.doc, or Myans.doc.
regex:MyPics[0-9].png Match MyPics followed by any digit, followed by .png. For
example, MyPics0.png, MyPics1.png, and MyPics9.png

The Sample Code Snippet

[java]

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PathMatcherSample implements FileVisitor<Path> {

private Map<String, List<String>> data = new HashMap<>();
private final PathMatcher pathMatcher;

public PathMatcherSample(final String pattern) {
this.pathMatcher = FileSystems.getDefault().getPathMatcher(“glob:” + pattern);
}

private boolean findFile(final Path file) {
if (pathMatcher.matches(file.getFileName()))
return Boolean.TRUE;
return Boolean.FALSE;
}

private void addToData(final String folderName, final String fileName) {
if (data.get(folderName) != null) {
data.get(folderName).add(fileName);
} else {
List<String> fileData = new ArrayList<>();
fileData.add(fileName);
data.put(folderName, fileData);
}
}

public Map<String, List<String>> getData() {
return data;
}

@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (findFile(file)) {
final String folderName = file.getParent().toString();
final String fileName = file.getFileName().toString();
addToData(folderName, fileName);
}
return FileVisitResult.CONTINUE;
}

@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.SKIP_SUBTREE;
}

@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}

public static void main(String[] args) throws IOException {
Path path = Paths.get(“C:/”);
final String pattern = “*.{java, class}”;
PathMatcherSample sample = new PathMatcherSample(pattern);
Files.walkFileTree(path, sample);
Map<String, List<String>> pathData = sample.getData();
for (String obj : pathData.keySet()) {
System.out.println(“+Folder: ” + obj);
List<String> directoryFiles = pathData.get(obj);
for (String file : directoryFiles)
System.out.println(“\t -File Name: ” + file);
}
}
}

[/java]