直接来自 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/