何时在 JAVA 中的 glob 语法中使用 **(双星) [英] When to use ** (double star) in glob syntax within JAVA
问题描述
直接来自这个 Java Oracle 教程:
<块引用>两个星号 ** 的作用与 * 类似,但跨越目录边界.这语法一般用于匹配完整路径.
有人能举出一个真实的例子吗?跨目录边界"是什么意思?跨越目录边界,我想像检查从根目录到 getNameCount()-1
的文件.再举一个真实的例子来解释实践中 * 和 ** 之间的区别会很棒.
FileSystem#getPathMatcher()
有一些很好的例子和解释
*.java 匹配表示以 .java 结尾的文件名的路径*.* 匹配包含点的文件名*.{java,class} 匹配以 .java 或 .class 结尾的文件名富.?匹配以 foo 开头的文件名.和单个字符扩展/home/*/* 在 UNIX 平台上匹配/home/gus/data/home/** 在 UNIX 平台上匹配/home/gus 和/home/gus/dataC:\* 在 Windows 平台上匹配 C:foo 和 C:ar(注意反斜杠被转义;作为 Java 语言中的字符串文字,模式将是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("路径:"+路径+"");如果(pathMatcher.matches(路径)){System.out.print(匹配");}System.out.println();});
如果使用 **
,它将匹配该目录中的所有文件夹和文件.
Directly from this Java Oracle tutorial:
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 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:ar 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.
这篇关于何时在 JAVA 中的 glob 语法中使用 **(双星)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!