[英]How to get the jar files in the specified directory and why is PathMatcher not working?
I'm trying to get *.jar
files in a specified directory (no recursing subdirectories), I think my code is no problem, but the results are incomprehensible, am I doing something wrong?我试图在指定目录(没有递归子目录)中获取*.jar
文件,我认为我的代码没有问题,但结果令人费解,是我做错了什么吗?
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
public class Test {
private static final PathMatcher JAR_FILE_MATCHER = FileSystems.getDefault().getPathMatcher("glob:*.jar");
public static void main(String[] args) throws IOException {
List<Path> list = new ArrayList<>();
Files.walkFileTree(Path.of("E:/lib"), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (JAR_FILE_MATCHER.matches(file)) list.add(file);
else System.out.println("[mismatched] " + file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) {
return FileVisitResult.CONTINUE;
}
});
System.out.printf("Total: %d jar files found!%n", list.size());
}
}
The output:
[mismatched] E:\lib\commons-lang3-3.12.0.jar
[mismatched] E:\lib\log4j-api-2.18.0.jar
[mismatched] E:\lib\log4j-core-2.18.0.jar
[mismatched] E:\lib\ojdbc6-12.1.0.1-atlassian-hosted.jar
[mismatched] E:\lib\spring-web-5.3.22.jar
Total: 0 jar files found!
What is a better way to scan a specified directory for jars?扫描 jars 的指定目录有什么更好的方法?
Thanks in advance:)提前致谢:)
You should use the find version for your case:您应该为您的案例使用find版本:
try (Stream<Path> s = Files.find(Path.of("E:/lib"),
1 /* see below */,
(path, attrs) -> JAR_FILE_MATCHER.matches(file)
)) {
var list = s.toList();
}
The 1 is the maximum depth: if you don't want to scan recursively, a value of 1 would avoid that. 1 是最大深度:如果您不想递归扫描,则值为 1 可以避免这种情况。
The list is another alternative, although it also returns directories and filtering files do have a cost:该列表是另一种选择,尽管它也返回目录和过滤文件确实有成本:
try (Stream<Path> s = Files.list(Path.of("E:/lib"))) {
var list = s.filter(JAR_FILE_MATCHER::matches)
.filter(Files::isRegularFile)
.toList();
}
The problem is PathMatcher that you defined.问题是您定义的 PathMatcher。
private static final PathMatcher JAR_FILE_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*.jar");
will work because '**' matches any string, including sub-path (like E:/lib in you example):)将起作用,因为 '**' 匹配任何字符串,包括子路径(例如您的示例中的 E:/lib):)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.