仅在这两种方法中保持深度怎么preVisitDirectory
样postVisitDirectory
?您将在 中增加depth
和preVisitDirectory
减少它postVisitDirectory
。不过,您可能必须初始化depth
为-1
, 才能depth == 0
在开始目录中拥有 when 。这样,您将始终拥有正确的depth
.
编辑:如果你返回SKIP_SIBLINGS
from visitFile
,而不是 from preVisitDirectory
,postVisitDirectory
仍然会被调用!
这是一个代码示例:
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);
}
}