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

(kavin kankeshwar) #1

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 ?

(Peter Niederwieser) #2

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

(kavin kankeshwar) #3

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

(Peter Niederwieser) #4

Something like:

configurations {
  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 // assuming top-level json object has an 'info' property

(kavin kankeshwar) #5

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.

(Peter Niederwieser) #6

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.

(kavin kankeshwar) #7

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

(davidmichaelkarr) #8

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?

(Peter Niederwieser) #9

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.