JimEvans
JimEvans

Reputation: 27496

How can I use a glob in Java to match files in directory and subdirectories?

I have a situation where I need to match files along a specific path, and capture all files matching in that directory and any subdirectories. As a requirement, I must start from a base root directory, and that path is immutable. For example, assume that I have some/root/dir/foo/bar.java and some/root/dir/foo/baz/quux.java. If I attempt to run the following code, I do not get the results I desire:

private static void findMe(String srcPath, String matcherPattern) throws IOException {
  final List<Path> filePaths = new ArrayList<>();
  final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(matcherPattern);
  Files.walkFileTree(srcPath, new SimpleFileVisitor<>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      if (matcher.matches(file)) {
        filePaths.add(file);
      }
      return FileVisitResult.CONTINUE;
    }
  });
  filePaths.forEach(filePath -> System.out.println(filePath.toString()));
}

Given my requirements, I must use "some/root" as my value for the srcPath argument. However, if I use findMe("some/root", "glob:**/foo/*.java"), I get only my first file; if I use findMe("some/root", "glob:**/foo/**/*.java"), I get only my second file. Is what I'm trying to do just not possible with a glob? I'd be more than happy to replace the glob with a regex, if I can accomplish it that way, but I'm unsure how to structure that regex either.

Upvotes: 0

Views: 2390

Answers (1)

Aaron
Aaron

Reputation: 24812

Your first glob didn't match the second file because there was no ** between /foo and .java to match the potential subdirectories.

Your second glob didn't match the first file because there were two slashes between /foo and .java that couldn't be matched for .java files at the root of /foo/

I suggest using /foo/**.java if the foo directory is always at the root of the directory you are searching in, or **/foo/**.java otherwise.

Upvotes: 2

Related Questions