【发布时间】:2019-04-14 17:07:47
【问题描述】:
我想遍历一个包含许多子目录的目录树。我的目标是打印除 subdir 和 anotherdir 子目录中的所有 .txt 文件。 我可以使用下面的代码来实现这一点。
public static void main(String[] args) throws IOException {
Path path = Paths.get("C:\\Users\\bhapanda\\Documents\\target");
Files.walkFileTree(path, new Search());
}
private static final class Search extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");
PathMatcher pm1 = FileSystems.getDefault().getPathMatcher("glob:**\\anotherdir");
if (pm.matches(dir) || pm1.matches(dir)) {
System.out.println("matching dir found. skipping it");
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:*.txt");
if (pm.matches(file.getFileName())) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
}
但是当我尝试将 pm 和 pm1 PathMatchers 与以下代码组合时,它不起作用。
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");
if (pm.matches(dir)) {
System.out.println("matching dir found. skipping it");
return FileVisitResult.SKIP_SUBTREE;
} else {
return FileVisitResult.CONTINUE;
}
}
glob 语法有什么问题吗?
【问题讨论】:
-
请阅读minimal reproducible example 并相应地增强您的问题。 “不工作”不是一个有效的问题描述。
标签: java nio simplefilevisitor