I'm using the following JAVA 8 code to delete a directory and its contents (files, subdirectories and directory). If I want to refactor the code in order to preserve the directory and erase only its content, how can I achieve this?
Path pathToBeDeleted = Paths.get(directoryPath);
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
You need to add a filter to your stream (before the map operation):
filter(path -> !path.equals(pathToBeDeleted))
This will return a stream consisting of the directory contents only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With