5

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

hsz
  • 148,279
  • 62
  • 259
  • 315
  • In pure Java, or would you be willing to look at third party implementations? – Boris the Spider Jul 10 '14 at 13:23
  • I preffer pure Java. However 3rd party libs also can be acceptable. – hsz Jul 10 '14 at 13:24
  • 1
    You might be able to hack [`FileSystem.getPathMatcher`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)) to your needs. – Boris the Spider Jul 10 '14 at 13:24
  • @BoristheSpider Thanks. However it's available since Java 1.7 - I didn't mentioned about it - I have to compile it with Java 1.6 – hsz Jul 10 '14 at 13:27
  • It is not available in 1.6 (see http://stackoverflow.com/questions/1247772/is-there-an-equivalent-of-java-util-regex-for-glob-type-patterns). Why do you prohibit yourself to use the 'glob-to-regex' technique ? You can also use the [wildcard](https://github.com/EsotericSoftware/wildcard) library – superbob Jul 10 '14 at 13:30

3 Answers3

7

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.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
4

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
Mincong Huang
  • 5,284
  • 8
  • 39
  • 62
3

To add to the previous answer: org.apache.commons.io.FilenameUtils.wildcardMatch(filename, wildcardMatcher) from Apache commons-lang library.

Alexander
  • 2,761
  • 1
  • 28
  • 33