根据Java8文档,可以实现接口FileVisitor
或者继承类SimpleFileVisitor
来遍历文件。
比如下面的代码,可以遍历目录,并把每个文件的路径添加到Set中。
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
public class MyFileVisitor extends SimpleFileVisitor<Path> {
private Set<String> pathStringSet = new HashSet<>();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
pathStringSet.add(file.toString());
return FileVisitResult.CONTINUE;
}
public Set<String> getPathStringSet() {
return pathStringSet;
}
}
这样启动:
public static void main(String[] args) {
Path a = Paths.get("/Users/xxx/Downloads");
MyFileVisitor mfv = new MyFileVisitor();
Files.walkFileTree(start, mfv);
System.out.println(mfv.getPathStringSet());
}
再举个例子,下面的代码,可以删除所有的空目录:
import java.io.IOException;
import java.nio.file.*;
public class DeleteEmptyDirVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws Exception {
if (Files.isDirectory(dir)) {
try {
Files.delete(dir);
} catch (DirectoryNotEmptyException ignored) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return FileVisitResult.CONTINUE;
}
}
这样启动:
public static void main(String[] args) {
Path a = Paths.get("/Users/xxx/Downloads");
DeleteEmptyDirVisitor mfv = new DeleteEmptyDirVisitor();
Files.walkFileTree(start, mfv);
}