Java SimpleFileVisitor遍历目录树以查找除两个子目录外的所有.txt文件
我想遍历一个有许多子目录的目录树。我的目标是打印所有的.txt文件,除了那些在subdir和另一个子目录中的文件。 我可以用下面的代码实现这一点Java SimpleFileVisitor遍历目录树以查找除两个子目录外的所有.txt文件,java,nio,simplefilevisitor,Java,Nio,Simplefilevisitor,我想遍历一个有许多子目录的目录树。我的目标是打印所有的.txt文件,除了那些在subdir和另一个子目录中的文件。 我可以用下面的代码实现这一点 public static void main(String[] args) throws IOException { Path path = Paths.get("C:\\Users\\bhapanda\\Documents\\target"); Files.walkFileTree(path, new Search()); } p
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;
}
}
glob语法有问题吗?是的,glob语法有问题。您需要将每个反斜杠加倍,以便它们在glob模式中保持转义反斜杠 第一个匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");
与以\subdir
结尾的路径不匹配。相反,在glob模式中,双斜杠变成了单斜杠,这意味着“s”被转义。由于转义的“s”只是“s”,因此该匹配器相当于:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**subdir");
这意味着它将匹配以子目录
结尾的任何路径。因此,它将匹配路径xxx\subdir
,但也将匹配路径xxx\xxxsubdir
和xxxsubdir
组合匹配器:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");
他也有同样的问题。在本例中转义的是“{”。在全局模式中,这意味着将“{”视为文字字符,而不是模式组的开头。因此,此匹配器将不匹配路径xxx\subdir
,但它将匹配路径xxx{subdir,anotherdir}
这两个匹配器将执行预期的操作:
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\subdir");
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\{subdir,anotherdir}");
请阅读并相应增强您的问题。“不工作”不是工作问题描述。
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\subdir");
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\{subdir,anotherdir}");