When to use ** (double star) in glob syntax within JAVA

放肆的年华 提交于 2019-11-28 16:11:25

The javadoc for FileSystem#getPathMatcher() has some pretty good examples and explanations

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

*.{java,class}  Matches file names ending with .java or .class 
foo.?           Matches file names starting with foo. and a single character extension 
/home/*/*       Matches /home/gus/data on UNIX platforms 
/home/**        Matches /home/gus and /home/gus/data on UNIX platforms 
C:\\*           Matches C:\foo and C:\bar on the Windows platform (note that the backslash is escaped; as a string literal in the Java Language the pattern would be "C:\\\\*")  

So /home/** would match /home/gus/data, but /home/* wouldn't.

/home/* is saying every file directly in the /home directory.

/home/** is saying every file in any directory inside /home.


Example of * vs **. Assuming your current working directory is /Users/username/workspace/myproject, then the following will only match the ./myproject file (directory).

PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:/Users/username/workspace/*");
Files.walk(Paths.get(".")).forEach((path) -> {
    path = path.toAbsolutePath().normalize();
    System.out.print("Path: " + path + " ");
    if (pathMatcher.matches(path)) {
        System.out.print("matched");
    }
    System.out.println();
});

If you use **, it will match all folders and files within that directory.

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