How to know when the last file is being visited in FileVisitor?
-
04-06-2021 - |
Question
I need to do something with the file visited last in a directory. How can I know if the current call to my visitFile()
is the last one?
(I only want to list all the files and directories in a given directory. To do so, I've introduced a depth
field to my FileVisitor
implementation and in the preVisitDirectory
I return SKIP_SUBTREE
if the depth is greater than 0. (And then increment the depth
.) The problem is that I don't know when to reset the depth
to 0, because when I call the walkFileTree
with this FileVisitor implementation for another directory, the depth
is already > 0 and it only lists the given directory.)
Solution
How about maintaining the depth only within the two methods, preVisitDirectory
and postVisitDirectory
? You'll increment depth
in preVisitDirectory
and decrement it in postVisitDirectory
. You might have to initialize depth
to -1
, to have depth == 0
when in the start directory though. That way, you'll always have the right depth
.
Edit: If you return SKIP_SIBLINGS
from visitFile
, instead of from preVisitDirectory
, the postVisitDirectory
will still get called!
Here's a code sample:
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);
}
}