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

标签 java path nio glob matcher

直接来自 this Java Oracle 教程:

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

任何人都可以做一个真实的例子吗? “跨越目录边界”是什么意思? 跨越目录边界,我想像检查文件从根目录到 getNameCount()-1。 在 practice 中再举一个真实的例子来解释 * 和 ** 之间的区别会很棒。

最佳答案

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

*.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/*不会。

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

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


* 的示例与 ** .假设您当前的工作目录是 /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();
});

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

关于java - 何时在 JAVA 的 glob 语法中使用 **(双星),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722471/

相关文章:

Java-JUnit怎么办?

java - 沿直线移动对象

java - Netty 4 中的直接内存使用

java - 解析 java.nio.files.Path 时忽略前导斜杠的最佳方法是什么

java - Byte[] 用作 BufferInputStream 可以,但是

java - 如何使用for循环计算字符串中空格分隔符的数量?

java - Spring根据当前范围注入(inject)不同的bean

java - JasperReports 神秘的收获值

bash - 无法将 $PWD 与 sed、bash 一起使用

python - Python 中包含路径的自然排序列表