您可以结合使用NIO 2和Stream API。
Path rootPath = Paths.get("/data/to-delete");// before you copy and paste the snippet// - read the post till the end// - read the javadoc to understand what the pre will do //// a) to follow softlinks (removes the linked file too) use// Files.walk(rootPath, FileVisitOption.FOLLOW_linkS)//// b) to not follow softlinks (removes only the softlink) use// the snippet belowtry (Stream<Path> walk = Files.walk(rootPath)) { walk.sorted(Comparator.reverseOrder()) .map(Path::toFile) .peek(System.out::println) .forEach(File::delete);}Files.walk
-返回以下所有文件/目录,rootPath
包括.sorted
-以相反的顺序对列表进行排序,因此目录本身位于包含子目录和文件的后面.map
-映射Path
到File
.peek
-仅显示要处理的条目.forEach
-.delete()
在每个File
对象上调用方法
编辑 正如@Seby首先提到的,现在由@JohnDough引用的,
Files.walk()应该在
try-with-resource构造中使用。多亏了两者。
从Files.walk javadoc
如果需要及时处理文件系统资源,则应使用try-with-resources构造来确保流操作完成后调用流的close方法。
编辑
这是一些数字。 该目录
/data/to-delete包含解压缩
rt.jar的jdk1.8.0_73和最新版本的activemq。
files: 36,427dirs : 4,143size : 514 MB
时间(以毫秒为单位)
int. SSD ext. USB3NIO + Stream API 1,126 11,943FileVisitor 1,362 13,561
两种版本均执行时未打印文件名。最大的限制因素是驱动器。没有执行。
编辑
有关选项的一些其他信息
FileVisitOption.FOLLOW_linkS。
假设以下文件和目录结构
/data/dont-delete/bar/data/to-delete/foo/data/to-delete/dont-delete -> ../dont-delete
使用
Files.walk(rootPath, FileVisitOption.FOLLOW_linkS)
将遵循符号链接,该文件
/tmp/dont_delete/bar也将被删除。
使用
Files.walk(rootPath)
将不会遵循符号链接,并且
/tmp/dont_delete/bar不会删除该文件。
注意: 切勿在不了解代码功能的情况下将代码用作复制和粘贴。



