Search code examples
javafilegradlegroovy

How to get the built jar file after the build task in the form of java.io.File object?


I am trying to extend the build task with the name buildAndPost, which after the build completes, copies the file to the required destination and connects to the server triggering a reload mechanism that automatically reloads the installed plugins (it is also a plugin).
So far I am done with all the code, but one thing is stopping me.
That is, I am accessing the jar file with the following groovy code in build.gradle:

task buildAndPost{
    dependsOn build
    
    doLast{
        File builtFile = tasks.jar.archiveFile.get(); // <----- Here is the problem -----
        PostBuildAction action = new PostBuildAction(builtFile, $serverDir);
    }
}

for my part of code to work that I purely wrote in java at very below of my build script, it requires the file that is built after performing the build task in the form of Java File object, i.e. java.io.File.

but the line tasks.jar.archiveFile.get() returns an object of something from groovy or gradle api that I currently don't know.
Using groovy is not my forte (at least the part added more to this java's superset), and I barely understand it.

How can I get that file as a Java's File or java.io.File object?


Solution

  • This isn't so much a Groovy thing but solved by looking at the documentation.

    The task jar created by the Java plugin is of type Jar. You can consult Jar's API in Gradle's published Javadocs which show that Jar has a getter method getArchiveFile() which returns a Provider<RegularFile>. (This is the method you call when you access the property archiveFile in Groovy, via its field-access notation.)

    In turn, a RegularFile has a method getAsFile() which returns the underlying File object.

    So to get the File you can call:

    tasks.jar.archiveFile.get().getAsFile()
    

    Or in fact

    tasks.jar.archiveFile.get().asFile
    

    would also work in Groovy, again using the abbreviated syntax for calling Java getters.