menteith
menteith

Reputation: 678

Getting files of certain extension using PathMatcher

I'd like to get all *.pdf files from a directory (and not also with its subdirectories). I use FileSystems.getDefault().getPathMatcher( "glob:**.pdf"), but it works recursively.

EDIT

I've already tried FileSystems.getDefault().getPathMatcher( "glob:*.pdf") but this give me no files (but there are *.pdf files in a given directory).

Upvotes: 1

Views: 1178

Answers (2)

sn42
sn42

Reputation: 2444

From the docs:

*.java Matches a path that represents a file name ending in .java

So the path matcher for glob:*.java will only return true for actual file names (e.g. x.pdf), which are returned by Path.getFileName() for example.

A possible solution to your problem of iterating PDF files in a directory without subdirectories may be limitting the depth of file tree traversal instead of changing the behaviour of the matcher.

Path start = Paths.get("C:/Users/maxim/Desktop/test/");
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**.pdf");
Files.walk(start, 1)
    .filter(matcher::matches)
    .forEach(System.out::println);

Upvotes: 1

cse
cse

Reputation: 4104

The problem is in using glob patterns.

Use FileSystems.getDefault().getPathMatcher( "glob:*.pdf") instead of FileSystems.getDefault().getPathMatcher( "glob:**.pdf").

Following is an extract from Javadoc:

The following rules are used to interpret glob patterns:

  • The * character matches zero or more characters of a name component without crossing directory boundaries.
  • The ** characters matches zero or more characters crossing directory boundaries.

Upvotes: 0

Related Questions