Java.nio: most concise recursive directory delete

前端 未结 6 861
日久生厌
日久生厌 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:07

    Files.walk(pathToBeDeleted).sorted(Comparator.reverseOrder()).forEach(Files::delete);
    

    You'll need the "try with resources" pattern to close the stream if "timely disposal of file system resources is required".

    Also, probably an unwelcome comment, but it would be much cleaner and more readable to use a library. With the code in a shared function, it won't take up much space. Every person who looks at your code must validate that this code does a proper delete, and its by no means obvious.

提交回复
热议问题