Java.nio: most concise recursive directory delete

前端 未结 6 876
日久生厌
日久生厌 2020-12-13 06:10

I am currently trying to recursively delete a directory... Strangely enough the shortest piece of code I was able to find is the following construct, employing an ad-hoc

6条回答
  •  不思量自难忘°
    2020-12-13 07:05

    The following solution doesn't need the conversion from Path to File objects:

    Path rootPath = Paths.get("/data/to-delete");     
    final List pathsToDelete = Files.walk(rootPath).sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    for(Path path : pathsToDelete) {
        Files.deleteIfExists(path);
    }
    

提交回复
热议问题