简体   繁体   English

Files.walkFileTree中的遍历顺序

[英]Order of traversal in Files.walkFileTree

What is the order in which Files.walkFileTree visits files/directories at the same level? Files.walkFileTree访问同一级别的文件/目录的顺序是什么?

It doesn't appear to visit them in order of size, last modified time or name. 它似乎没有按大小,上次修改时间或名称的顺序访问它们。 I couldn't find anything in the API documentation either. 我在API文档中也找不到任何内容。

Perhaps the preVisitDirectory method can be used to specify the order of visit but what is default behaviour ? 也许preVisitDirectory方法可用于指定访问顺序但默认行为是什么?

The order in which the subdirectories are read is not defined as per this comment in the Java Tutorial : 读取子目录的顺序未按照Java教程此注释定义:

A file tree is walked depth first, but you cannot make any assumptions about the iteration order that subdirectories are visited. 首先深度遍历文件树,但是您不能对访问子目录的迭代顺序做出任何假设。

As for the order in which the files are read, it depends (in the current implementation) on the supplied DirectoryStream , which is sun.nio.fs.WindowsDirectoryStream on my computer. 至于文件的读取顺序,它取决于(在当前实现中)提供的DirectoryStream ,即我的计算机上的sun.nio.fs.WindowsDirectoryStream Reading the javadoc of DirectoryStream , you will see that: 阅读DirectoryStream的javadoc ,您将看到:

The elements returned by the iterator are in no specific order. 迭代器返回的元素没有特定的顺序。

java can sort it for you later, here is what I did. java可以在以后为你排序,这就是我做的。

public static void printy(Path rootDirPath) {
        //treesets to hold paths alphabetically
        TreeSet<Path> paths = new TreeSet<>();
        try {
            Files.walkFileTree(rootDirPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    paths.add(dir);
                    return super.preVisitDirectory(rootDirPath, attrs);
                }
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    paths.add(file);
                    return super.visitFile(rootDirPath, attrs);
                }
                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    return super.visitFileFailed(file, exc);
                }
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    return super.postVisitDirectory(rootDirPath, exc);
                }
            });
        //I'm printing the contents alphabetically,.. your impl might vary
        paths.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM