Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the contents of a directory (files and subdirectory) without deletecting the directory itself with Java NIO?

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);
like image 716
Alexandra Bradan Avatar asked Jan 22 '26 18:01

Alexandra Bradan


1 Answers

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.

like image 166
Boris Avatar answered Jan 24 '26 11:01

Boris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!