Match path string using glob in Java

冷暖自知 提交于 2019-12-12 16:12:57

问题


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


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/24677662/match-path-string-using-glob-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!