How to Delete a directory tree excluding certain sub-directory using Gradle?

My directory structure is as below:

dir -|
     |
     - sub_dir1 -|
     |           |
     |           - file1
     |
     - sub_dir2 -|
     |           |
     |           - file2
     |
     - sub_dir3 -|
                 |
                 - file3

I want to recursively delete all content of dir except content of sub-dir1

So the expected resulting directory structure should be as below:

dir -|
     |
     - sub_dir1 -|
                 |
                 - file1

I have tried following code and it deleting all the files except the content of sub_dir1. However it is not deleting the other sub directories but only the files within those directories.

delete fileTree(dir: "dir1").exclude("sub_dir1").include('**/**')

Result of above code:

dir -|
     |
     - sub_dir1 -|
     |           |
     |           - file1
     |
     - sub_dir2 
     |           
     |
     - sub_dir3

How can I delete these directories too along with the files contained by them?

I tried this and it seems to work. Notice that instead of passing fileTree result, I call delete on each matching file in visit{}:

task deleteFolder(type: Delete) {
    fileTree(dir: 'dir1').exclude("sub_dir1").visit { FileVisitDetails details ->
        delete details.file
    }
}

I didn’t understand why what you wrote didn’t work. When printing the files in the file tree with each {}, I saw it didn’t list any folder, even if I removed the exclude() call. When calling visit {} it did print the folders. The difference, related to folders, is mentioned in the documentation of these methods.

delete fileTree('dir1').matching {
   exclude 'sub_dir1/**' 
} 
1 Like