![](/img/trans.png)
[英]How to delete all files in a directory java android app? Current code is deleting the that folder
[英]Delete all files and subdirectories but keep the current directory empty in Java
我有一個文件夾“/ a / b /”,我想刪除文件夾b中的所有內容,包括這些目錄中的文件,目錄和文件以及子目錄,但我想保留文件夾b為空而不刪除它。 我試過的是:
Files.walk(Paths.get("/a/b/"))//
.map(Path::toFile)//
.sorted(Comparator.comparing(File::isDirectory))//
.forEach(File::delete);
當它刪除文件夾b中的所有內容時,此解決方案工作正常,但它也刪除了我想保留的文件夾b。 我應該如何更改此處以保留文件夾b,任何人都可以給我一個提示嗎? 謝謝
過濾除此目錄之外的所有目
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())
您可以使用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,流也不會關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.