首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SimpleFileVisitor遍历目录树以查找除两个子目录之外的所有.txt文件

使用SimpleFileVisitor遍历目录树以查找除两个子目录之外的所有.txt文件
EN

Stack Overflow用户
提问于 2019-04-14 15:49:17
回答 1查看 222关注 0票数 1

我想遍历包含许多子目录的目录树。我的目标是打印所有的.txt文件,除了那些在subdir和另一个and子目录中的文件。我可以用下面的代码来实现这一点。

代码语言:javascript
复制
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时,它不起作用。

代码语言:javascript
复制
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语法有什么问题吗?

EN

回答 1

Stack Overflow用户

发布于 2019-04-14 16:42:33

是的,glob语法有问题。您需要将每个反斜杠加倍,以便它们在glob模式中保持转义反斜杠。

第一个匹配器:

代码语言:javascript
复制
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\subdir");

与以\subdir结尾的路径不匹配。相反,在glob模式中,双斜杠变成了单斜杠,这意味着“s”正在被转义。因为转义的's‘只是一个's',所以这个匹配器等同于:

代码语言:javascript
复制
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**subdir");

这意味着它将匹配任何以subdir结尾的路径。因此,它将匹配路径xxx\subdir,但也将匹配路径xxx\xxxsubdirxxxsubdir

组合匹配器:

代码语言:javascript
复制
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\{subdir,anotherdir}");

也有同样的问题。在这种情况下,转义的是'{‘。在glob模式中,这意味着将'{‘视为文字字符,而不是模式组的开头。所以这个匹配器不会匹配路径xxx\subdir,但是它会匹配路径xxx{subdir,anotherdir}

这两个匹配器将执行预期的操作:

代码语言:javascript
复制
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\subdir");
PathMatcher pm = FileSystems.getDefault().getPathMatcher("glob:**\\\\{subdir,anotherdir}");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55673100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档