Delete all subdirectory except a subtree

Hi, I’m new.
I’m trying ti create a gradle task that delete all directory except a subset of those.

this is my situation
src/main/java
test/package1
test/package2
com/package3
com/package4
it/package5

and here my code:

task deleteFolders(type: Delete){

group = 'build'
if(currentTask == "deleteFolders"){ 



    def ftree=fileTree(dir: "$javaDir").exclude('test/package2')
    ftree.exclude('test/package1')
    ftree.visit { FileVisitDetails details ->

        delete  details.file
        }

}

but this code delete everythingh, also the packages inside “exclude”.

trying whith this other code

task deleteFolders{//(type: Delete)

group = 'build'
if(currentTask == "deleteFolders"){ 
 delete fileTree(dir: "$javaDir").matching {
		 exclude 'test/package1/**' 
		 exclude 'test/package2/**'
		}
                      }

everything work but the com folder is still there empty (i want to remove it).

so, can someone help me to reach this result ?

src/main/java
test/package1
test/package2

thanks a lot Leo