How to read a text/json file from a dependency jar?

I have dependency Jar which contains important information like git SHA and other relevant stuff. I would like to read this on projects which have dependency on it. This is helpful when using SNAPSHOT dependency.

Please can you point me how i could read file within a jar, which is configured as a dependency ?

You’d download the jar by resolving the configuration, unzip the jar (or just the file), and read the file.

Thanks!! Is there an example or sample code i could take inspiration from ?

Something like:

configurations {
  myConfig
}
  dependencies {
  myConfig "my:dependency:1.0@jar"
}
  task extractFile(type: Copy) {
  from { zipTree(myConfig.singleFile) }
  into "$buildDir/extract"
  include "my/file.json"
}
  task printInfo {
  dependsOn extractFile
  doLast {
    def slurper = new JsonSlurper()
    slurper.parse(file("$buildDir/extract/my/file.json"), "utf-8")
    println slurper.info // assuming top-level json object has an 'info' property
  }
}

Thank you very much! Is it possible to avoid extracting and reading directly, The way we can do on Linux ?

Would be great if i can avoid unzipping the dependencies.

This should only extract the file of interest, and should perform reasonably well. If your tests show that the performance isn’t good enough, you could try to write your own custom task.

Thank you very much ! let me trying Extracting. If not will dig into creating task.

Isn’t it also true that by separating this task into two tasks, if the dependencies haven’t changed, it will consider the extractFile task to be up to date (skipping it), allowing better performance, especially if printInfo will be executed much more often than the dependency changes?

Yes, but extracting a single file from a Zip can be made to be very fast, and if Gradle implemented this inefficiently (which afaik it doesn’t), a custom implementation could do better.