何时在 JAVA 中的 glob 语法中使用 **(双星)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18722471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:29:42  来源:igfitidea点击:

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

javapathnioglobmatcher

提问by Rollerball

Directly from thisJava Oracle tutorial:

直接来自这个Java Oracle 教程:

Two asterisks, **, works like * but crosses directory boundaries. This syntax is generally used for matching complete paths.

两个星号 ** 的作用与 * 类似,但跨越目录边界。此语法通常用于匹配完整路径。

Could anybody do a real example out of it? What do they mean with "crosses directory boundary"? Crossing the directory boundary, I imagine something like checking the file from root to getNameCount()-1. Again a real example explaining the difference between * and ** in practicewould be great.

有人能举出一个真实的例子吗?“跨目录边界”是什么意思?跨越目录边界,我想像检查文件从 root 到getNameCount()-1. 再一次解释 * 和 ** 在实践中的区别的真实例子会很棒。

采纳答案by Sotirios Delimanolis

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

javadoc forFileSystem#getPathMatcher()有一些很好的例子和解释

*.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/**会匹配/home/gus/data,但/home/*不会。

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

/home/*是说直接在/home目录中的每个文件。

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

/home/**是说里面的任何目录中的每个文件/home



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

的例子*VS **。假设您当前的工作目录是/Users/username/workspace/myproject,那么以下只会匹配./myproject文件(目录)。

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.

如果使用**,它将匹配该目录中的所有文件夹和文件。