[英]Delete all files and subdirectories but keep the current directory empty in Java
I have a folder "/a/b/" and I would like to delete everything inside of folder b, including files, directories and files and subdirectories inside of these directories, but I want to keep folder b empty without delete it. 我有一个文件夹“/ a / b /”,我想删除文件夹b中的所有内容,包括这些目录中的文件,目录和文件以及子目录,但我想保留文件夹b为空而不删除它。 What I have tried was:
我试过的是:
Files.walk(Paths.get("/a/b/"))//
.map(Path::toFile)//
.sorted(Comparator.comparing(File::isDirectory))//
.forEach(File::delete);
this solution worked fine when it deleted everything inside of folder b, but it deleted also folder b which I would like to keep. 当它删除文件夹b中的所有内容时,此解决方案工作正常,但它也删除了我想保留的文件夹b。 How should I change here to keep folder b, can anyone give me a tip?
我应该如何更改此处以保留文件夹b,任何人都可以给我一个提示吗? Thank you
谢谢
Filter all but this directory : 过滤除此目录之外的所有目
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);
Note that .sorted(Comparator.comparing(File::isDirectory))
may not be enough. 请注意
.sorted(Comparator.comparing(File::isDirectory))
可能还不够。
Deleting the directories in first instance matters but their deletion order matters too. 删除第一个实例中的目录很重要,但删除顺序也很重要。
Suppose you have directories : /a/b/
, /a/b/c
, /a/b/c/d
. 假设您有目录:
/a/b/
, /a/b/c
, /a/b/c/d
。
You want to delete directory depth-last before depth-first, that is /a/b/c/d
before /a/b/c
. 您想删除深度优先之前的目录深度,即
/a/b/c/d
之前的/a/b/c
。
But File.walk()
walks depth-first. 但
File.walk()
深度优先。 So it will iterate in the order : /a/b/
, /a/b/c
, /a/b/c/d
. 因此它将按顺序迭代:
/a/b/
, /a/b/c
, /a/b/c/d
。
So reverse the natural order of the stream of File
: 因此,反转
File
流的自然顺序:
.sorted(Comparator.reverseOrder())
You can use FileUtils from apache commons-io: 您可以使用apache commons-io中的FileUtils:
FileUtils.cleanDirectory(Paths.get("/a/b/").toFile());
Docs: org.apache.commons.io.FileUtils.cleanDirectory 文档: org.apache.commons.io.FileUtils.cleanDirectory
UPDATED: Only for knowledge, according to documentation for File.walks : 更新:根据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.
So, unless you use like this: 所以,除非你这样使用:
try(Stream<Path> paths = Files.walks(...)) {
//Operations here with paths
}
The stream will no close, even with forEach. 即使使用forEach,流也不会关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.