[英]How can I use a glob in Java to match files in directory and subdirectories?
I have a situation where I need to match files along a specific path, and capture all files matching in that directory and any subdirectories.我有一种情况,我需要沿特定路径匹配文件,并捕获该目录和任何子目录中匹配的所有文件。 As a requirement, I must start from a base root directory, and that path is immutable.
作为要求,我必须从基本根目录开始,并且该路径是不可变的。 For example, assume that I have
some/root/dir/foo/bar.java
and some/root/dir/foo/baz/quux.java
.例如,假设我有
some/root/dir/foo/bar.java
和some/root/dir/foo/baz/quux.java
。 If I attempt to run the following code, I do not get the results I desire:如果我尝试运行以下代码,我不会得到我想要的结果:
private static void findMe(String srcPath, String matcherPattern) throws IOException {
final List<Path> filePaths = new ArrayList<>();
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(matcherPattern);
Files.walkFileTree(srcPath, new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(file)) {
filePaths.add(file);
}
return FileVisitResult.CONTINUE;
}
});
filePaths.forEach(filePath -> System.out.println(filePath.toString()));
}
Given my requirements, I must use "some/root"
as my value for the srcPath
argument.鉴于我的要求,我必须使用
"some/root"
作为srcPath
参数的值。 However, if I use findMe("some/root", "glob:**/foo/*.java")
, I get only my first file;但是,如果我使用
findMe("some/root", "glob:**/foo/*.java")
,我只会得到我的第一个文件; if I use findMe("some/root", "glob:**/foo/**/*.java")
, I get only my second file.如果我使用
findMe("some/root", "glob:**/foo/**/*.java")
,我只会得到我的第二个文件。 Is what I'm trying to do just not possible with a glob?我想要做的事情是不可能用 glob 做的吗? I'd be more than happy to replace the glob with a regex, if I can accomplish it that way, but I'm unsure how to structure that regex either.
如果我能以这种方式完成它,我会非常乐意用正则表达式替换 glob,但我也不确定如何构建该正则表达式。
Your first glob didn't match the second file because there was no **
between /foo
and .java
to match the potential subdirectories.您的第一个 glob 与第二个文件不匹配,因为
/foo
和.java
之间没有**
来匹配潜在的子目录。
Your second glob didn't match the first file because there were two slashes between /foo
and .java
that couldn't be matched for .java
files at the root of /foo/
您的第二个 glob 与第一个文件不匹配,因为
/foo
和.java
之间有两个斜杠无法匹配/foo/
根目录下的.java
文件
I suggest using /foo/**.java
if the foo
directory is always at the root of the directory you are searching in, or **/foo/**.java
otherwise.如果
foo
目录始终位于您正在搜索的目录的根目录,我建议使用/foo/**.java
,否则使用**/foo/**.java
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.