Files.walkFileTree
访问同一级别的文件/目录的顺序是什么?
它似乎不会按大小、上次修改时间或名称的顺序访问它们。我在API documentation里也找不到任何东西。
也许preVisitDirectory
方法可以用来指定访问顺序,但是默认行为是什么呢?
发布于 2012-05-01 10:54:34
在the Java Tutorial中,读取子目录的顺序不是按照此注释定义的
首先对文件树进行深度遍历,但您不能对访问子目录的迭代顺序做出任何假设。
至于读取文件的顺序,它(在当前实现中)取决于提供的DirectoryStream
,即我的计算机上的sun.nio.fs.WindowsDirectoryStream
。阅读the javadoc of DirectoryStream
,您将看到:
迭代器返回的元素没有特定的顺序。
发布于 2018-03-23 06:14:51
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();
}
}
希望这能有所帮助
https://stackoverflow.com/questions/10396649
复制