[英]How to know when the last file is being visited in FileVisitor?
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? 我怎么知道当前对
visitFile()
调用是否是最后一次?
(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.) (我只想列出指定目录下的所有文件和目录。要做到这一点,我介绍了一个
depth
领域我FileVisitor
实施,并在preVisitDirectory
我回到SKIP_SUBTREE
如果深度大于0(然后递增depth
。)问题是我不知道何时将depth
重置为0,因为当我用另一个目录的FileVisitor实现调用walkFileTree
时, depth
已经> 0并且它只列出给定的目录。)
How about maintaining the depth only within the two methods, preVisitDirectory
and postVisitDirectory
? 如何仅在两个方法中保持深度,
preVisitDirectory
和postVisitDirectory
? You'll increment depth
in preVisitDirectory
and decrement it in postVisitDirectory
. 你会增加
depth
在preVisitDirectory
和递减它postVisitDirectory
。 You might have to initialize depth
to -1
, to have depth == 0
when in the start directory though. 您可能必须将
depth
初始化为-1
,以便在开始目录中具有depth == 0
。 That way, you'll always have the right depth
. 这样,你将永远拥有正确的
depth
。
Edit: If you return SKIP_SIBLINGS
from visitFile
, instead of from preVisitDirectory
, the postVisitDirectory
will still get called! 编辑:如果从
visitFile
返回SKIP_SIBLINGS
,而不是从preVisitDirectory
,则仍会调用postVisitDirectory
!
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);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.