Reputation: 152266
I have following string as a glob rule:
**/*.txt
And test data:
/foo/bar.txt
/foo/buz.jpg
/foo/oof/text.txt
Is it possible to use glob rule (without converting glob to regex) to match test data and return valud entries ?
One requirement: Java 1.6
Upvotes: 5
Views: 7154
Reputation: 5552
FileSystem#getPathMatcher(String)
is an abstract method, you cannot use it directly. You need to do get a FileSystem instance first, e.g. the default one:
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
Some examples:
// file path
PathMatcher m = FileSystems.getDefault().getPathMatcher("glob:**/*.txt");
m.matches(Paths.get("/foo/bar.txt")); // true
m.matches(Paths.get("/foo/bar.txt").getFileName()); // false
// file name only
PathMatcher n = FileSystems.getDefault().getPathMatcher("glob:*.txt");
n.matches(Paths.get("/foo/bar.txt")); // false
n.matches(Paths.get("/foo/bar.txt").getFileName()); // true
Upvotes: 4
Reputation: 2898
To add to the previous answer: org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher)
from Apache commons-lang
library.
Upvotes: 3
Reputation: 61168
If you have Java 7 can use FileSystem.getPathMatcher
:
final PathMatcher matcher = FileSystem.getPathMatcher("glob:**/*.txt");
This will require converting your strings into instances of Path
:
final Path myPath = Paths.get("/foo/bar.txt");
For earlier versions of Java you might get some mileage out of Apache Commons' WildcardFileFilter
. You could also try and steal some code from Spring's AntPathMatcher
- that's very close to the glob-to-regex approach though.
Upvotes: 7