首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何知道在FileVisitor中访问最后一个文件的时间?

如何知道在FileVisitor中访问最后一个文件的时间?
EN

Stack Overflow用户
提问于 2012-05-01 20:36:30
回答 1查看 1.2K关注 0票数 3

我需要对目录中最后访问的文件执行一些操作。我如何知道对visitFile()的当前调用是否是最后一个调用?

(我只想列出给定目录中的所有文件和目录。为此,我在FileVisitor实现中引入了depth字段,如果深度大于0,则在preVisitDirectory中返回SKIP_SUBTREE。(然后递增depth。)问题是我不知道何时将depth重置为0,因为当我使用这个FileVisitor实现为另一个目录调用walkFileTree时,depth已经大于0,并且它只列出了给定的目录。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-01 22:14:20

如果只在preVisitDirectorypostVisitDirectory这两个方法中保持深度呢?您将在preVisitDirectory中递增depth,在postVisitDirectory中递减它。您可能必须将depth初始化为-1,以便在启动目录中具有depth == 0。这样,您将始终拥有正确的depth

编辑:如果你从visitFile返回SKIP_SIBLINGS,而不是从preVisitDirectory返回,postVisitDirectory仍然会被调用!

下面是一个代码示例:

代码语言:javascript
复制
public class Java7FileVisitorExample {

public void traverseFolder(Path start){
    try {
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {

            private int depth = -1;

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                System.out.println("preVisitDirectory(" + dir + ")");
                depth++;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                if (depth > 0) {
                    return FileVisitResult.SKIP_SIBLINGS;
                }

                System.out.println("visitFile(" + file + ", " + attrs + "): depth == " + depth);

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e)
                    throws IOException {
                if (e == null) {
                    depth--;
                    System.out.println("postVisitDirectory(" + dir + ")");
                    return FileVisitResult.CONTINUE;
                } else {
                    throw e;
                }


            }
        });
    } catch (IOException ex) {
        Logger.getAnonymousLogger().throwing(getClass().getName(), 
                "traverseFolder", ex);
    }
}

public static void main(String... args) {
    Path start = Paths.get("/Book/Algorithm");
    new Java7FileVisitorExample().traverseFolder(start);
}

}

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10397711

复制
相关文章

相似问题

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