Is there a way to delete all files and folders from a directory but exclude the jar file?

Hi again,
I found a way to delete all files and folders from a directory ( in the doLast part ) but I’m wondering if I can get help modifying it so it excludes the jar file?

task copyJar(dependsOn:'sourceZip', type: Copy, description: "Copies jar File" ){
   // Removed copy code here 


    // Is there a way to exclude the jar file from this?
    doLast{
    def dirName ="${buildDir}/libs"
    file ( dirName ).list().each{
       f -> delete "${dirName}/${f}" 
        }
    }
}

Thank You!

Yes, you can use the project.delete(...) method with a FileCollection. This will delete everything, but JAR files:

project.delete(files("${buildDir}/libs") {
    exclude '*.jar'
})

However, based on your posts, your overall approach seems a bit abnormal. You seem to be copying a whole bunch of different things to same folder, archiving them, and trying to remove the extras along the way. Generally, intermediate artifacts would end up in different locations. You wouldn’t need to copy files from their original location just to archive them them and you wouldn’t need to remove items to get just the final artifact where you need it. A clean task would remove everything, and if something didn’t change the task would be UP-TO-DATE.

1 Like

However, based on your posts, your overall approach seems a bit abnormal. You seem to be copying a whole bunch of different things to same folder, archiving them, and trying to remove the extras along the way.

You are correct. Okay I need to rethink this. I’m trying to learn Gradle by doing so I’ll see if I can do all of this in an archive task.

Thank You!

Okay , just here to say Thank You! I created two archive tasks to create the binary and source and it worked perfectly! I appreciate your help with this .

1 Like