How to copy a folder from a dependent External Library's jar into the gradle project's jar?

I’ve a gradle project which has a dependency on an external library say “ext1.jar”. This external library has a folder “f1” which has some class files. When I build my gradle project I want to copy that folder “f1” from “ext1.jar” into my project’s jar.

I see that this works if I want to copy a single file in my src into jar:

jar {
    from "sampleFileInSrc.txt"
}

However I want to copy something from a dependent jar. Something like this:

jar {
    from library 'ext1.jar' and folder 'f1'
    into "src/main/resources"
}

Anyone knows how can this be done?

Hi @90abyss,

You can use zipTree() to work with the content of the jar rather than the jar file itself. Here is a complete example taking a jar from the classpath and packaging its content into your jar:

plugins {
    id 'java-library'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.apache.commons:commons-lang3:3.9'
}

jar {
    from provider {
        zipTree(configurations.compileClasspath.filter {
            it.name == 'commons-lang3-3.9.jar'
        }.singleFile)
    }
}
1 Like

@jendrik thanks fro your reply!

i tried this but it isn’t working ->

My gradle project has an external dependency. I want to include a class file from external dependency into my gradle project’s jar.

This class file “test.class” lives in a subdirectory within “my-lib.jar”.

This is my build.gradle:

dependencies {
    compile 'org.apache.commons:commons-lang3:3.9'
    testCompile 'my-lib'
}

jar {
    manifest {
        attributes("Implementation-Title": "com.my.modules#${project.name};${project.version}",
                "Implementation-Version": "${project.version}")
    }
	
	// this works but copies everything->
	from provider {
        zipTree(configurations.compileClasspath.filter {
            it.name == 'commons-lang3-3.9.jar'
        }.getAsPath())
    }
	
	// this doesn't ->
	from provider {
        zipTree(configurations.compileClasspath.filter {
            it.name == 'my-lib.jar'
        }.getAsPath())
    }
	
	// this doesn't either ->
	from provider {
        zipTree(configurations.testCompile.filter {
            it.name == 'my-lib.jar'
        }.getAsPath())
    } 
}

This is the error I’m getting:

Could not determine the dependencies of task ':jar'.
> path may not be null or empty string. path=''

How can I do this essentially?

Copy test.class from externaldependency my-lib.jar into my jar

1 Like

I endeded up doing:

it.name.contains(‘my-lib.jar’)
and now it seems to be working.

1 Like