public FileVisitResult postVisitDirectory(Path dir, IOException exec)
throws IOException {
// 访问文件夹之前调用
System.out.println("Just visited " + dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// 访问文件夹之后调用
System.out.println("About to visit " + dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// 访问文件后调用
if (attrs.isRegularFile())
System.out.print("Regular File:");
System.out.println(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
// 文件不可访问时调用
System.out.println(exc.getMessage());
return FileVisitResult.CONTINUE;
}
}
复制代码
测试代码:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestFileTree {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
MyFileVisitor visitor = new MyFileVisitor();
Files.walkFileTree(fileDir, visitor);
}
}
复制代码
运行:
C:\ex>java TestFileTree
About to visit files
About to visit files\newdir
Regular File:files\newdir\psum.txt
Just visited files\newdir
Regular File:files\backup.txt
Regular File:files\loremipsum.txt
Regular File:files\test.txt
Just visited files