Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match path string using glob in Java

Tags:

java

glob

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

like image 342
hsz Avatar asked Dec 25 '22 06:12

hsz


1 Answers

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.

like image 155
Boris the Spider Avatar answered Dec 28 '22 05:12

Boris the Spider