我想遍历包含许多子目录的目录树。我的目标是打印所有的.txt文件,除了那些在subdir和另一个and子目录中的文件。我可以用下面的代码来实现这一点。
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语法有什么问题吗?
发布于 2019-04-14 16:42:33
是的,glob语法有问题。您需要将每个反斜杠加倍,以便它们在glob模式中保持转义反斜杠。
第一个匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");与以\subdir结尾的路径不匹配。相反,在glob模式中,双斜杠变成了单斜杠,这意味着“s”正在被转义。因为转义的's‘只是一个's',所以这个匹配器等同于:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**subdir");这意味着它将匹配任何以subdir结尾的路径。因此,它将匹配路径xxx\subdir,但也将匹配路径xxx\xxxsubdir和xxxsubdir。
组合匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");也有同样的问题。在这种情况下,转义的是'{‘。在glob模式中,这意味着将'{‘视为文字字符,而不是模式组的开头。所以这个匹配器不会匹配路径xxx\subdir,但是它会匹配路径xxx{subdir,anotherdir}。
这两个匹配器将执行预期的操作:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\subdir");
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\{subdir,anotherdir}");https://stackoverflow.com/questions/55673100
复制相似问题