何时在JAVA的glob语法中使用**(双星) [英] When to use ** (double star) in glob syntax within JAVA

查看:339
本文介绍了何时在JAVA的glob语法中使用**(双星)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直接来自 Java Oracle教程:

Directly from this Java Oracle tutorial:

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

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

有人可以用它做一个真实的例子吗? 它们与跨越目录边界"是什么意思? 越过目录边界,我想像是要检查从根目录到getNameCount()-1的文件. 同样,一个真实的例子可以解释实践中*和**之间的区别.

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 practice would be great.

推荐答案

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:\\\\*")  

因此/home/**将与/home/gus/data匹配,但/home/*不会.

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

/home/*表示每个文件直接位于/home目录中.

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

/home/**表示/home内部任何目录中的每个文件.

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

***的示例.假设您当前的工作目录为/Users/username/workspace/myproject,则以下内容仅与./myproject文件(目录)匹配.

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.

这篇关于何时在JAVA的glob语法中使用**(双星)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆