我想列出目录和子目录中与文件掩码匹配的所有文件。
例如“M:\SOURCE\*.doc”,而 SOURCE 可能如下所示:
|-- SOURCE
| |-- Folder1
| | |-- File1.doc
| | |-- File1.txt
| |-- File2.doc
| |-- File3.xml
应该返回 File1.doc 和 File2.doc。
最初,我使用 DirectoryStream,因为它已经对掩码/glob 语法进行了一些检查,并且能够将其用于过滤,因为这 ISN'T 只是一些正则表达式,但普通用户更容易理解的实际文件掩码
Files.newDirectoryStream(path, mask);
问题是 DirectoryStream 只检查您提供的直接路径目录,不是它的子目录
THEN 带有 Files.walk 的“扁平化”方法,它实际上能够查看所有子目录,问题是,它不提供可以像 DirectoryStream 一样通过文件掩码“过滤”
Files.walk(path, Integer.MAX_VALUE);
所以我卡住了,无法在这里结合两种方法的优点...
最佳答案
您还可以使用自定义 FileVisitor
[1],结合 PathMatcher
[2],它与 GLOB 完美配合。
代码可能如下所示:
public static void main(String[] args) throws IOException {
System.out.println(getFiles(Paths.get("/tmp/SOURCE"), "*.doc"));
}
public static List<Path> getFiles(final Path directory, final String glob) throws IOException {
final var docFileVisitor = new GlobFileVisitor(glob);
Files.walkFileTree(directory, docFileVisitor);
return docFileVisitor.getMatchedFiles();
}
public static class GlobFileVisitor extends SimpleFileVisitor<Path> {
private final PathMatcher pathMatcher;
private List<Path> matchedFiles = new ArrayList<>();
public GlobFileVisitor(final String glob) {
this.pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + glob);
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
if (pathMatcher.matches(path.getFileName())) {
matchedFiles.add(path);
}
return FileVisitResult.CONTINUE;
}
public List<Path> getMatchedFiles() {
return matchedFiles;
}
}
[1] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/FileVisitor.html
[2] https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/PathMatcher.html
关于java - 列出目录中与文件掩码(又名模式或 Glob)匹配的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64826753/