删除所有文件和子目录,但在Java中将当前目录保留为空

时间:2018-08-31 07:52:02

标签: java file-io

我有一个文件夹“ / a / b /”,我想删除文件夹b内的所有内容,包括文件,目录以及这些目录内的文件和子目录,但是我想保持文件夹b为空而不删除它。我尝试过的是:

Files.walk(Paths.get("/a/b/"))//
                 .map(Path::toFile)//
                 .sorted(Comparator.comparing(File::isDirectory))//
                 .forEach(File::delete);

此解决方案在删除文件夹b内的所有内容时都可以正常工作,但同时也删除了我想保留的文件夹b。我该如何更改这里的文件夹b,谁能给我小费?谢谢

2 个答案:

答案 0 :(得分:4)

过滤除此目录外的所有内容:

Path rootPath = Paths.get("/a/b/");
Files.walk(rootPath)//
     .filter(p -> !p.equals(rootPath))
     .map(Path::toFile)//
     .sorted(Comparator.comparing(File::isDirectory))//
     .forEach(File::delete);

请注意,.sorted(Comparator.comparing(File::isDirectory))可能还不够。
首先删除目录很重要,但是删除顺序也很重要。

假设您具有目录:/a/b//a/b/c/a/b/c/d
您要删除深度优先之前的目录,即深度/a/b/c/d之前的/a/b/c
但是File.walk()走的是深度优先的。因此它将按照以下顺序进行迭代:/a/b//a/b/c/a/b/c/d
因此,颠倒File流的自然顺序:

 .sorted(Comparator.reverseOrder())

答案 1 :(得分:0)

您可以使用apache commons-io的FileUtils:

FileUtils.cleanDirectory(Paths.get("/a/b/").toFile()); 

文档:org.apache.commons.io.FileUtils.cleanDirectory

已更新:仅出于了解目的,根据 File.walks 的文档:

The returned stream encapsulates one or more {@link DirectoryStream}s.
 * If timely disposal of file system resources is required, the
 * {@code try}-with-resources construct should be used to ensure that the
 * stream's {@link Stream#close close} method is invoked after the stream
 * operations are completed.

因此,除非您这样使用:

try(Stream<Path> paths = Files.walks(...)) {
  //Operations here with paths
}

即使使用forEach,流也不会关闭。

相关问题