Gradle – working with files

When working with files in Gradle, the key classes are:

FileCollection
FileTree – which extends FileCollection

Getting a FileCollection

You can get a file collection by using the files() method which is always available (from the Project object).

FileCollection myFiles = files("someDirectory")

Getting a filtered list of files

If you want to filter, probably easier to use the FileTree:

FileTree myFiles = fileTree("someDirectory").matching {
	include "*.xsd"
}

Extracting files from a jar / dependency / zip

Sometimes you might need to extract files from a dependency in order to process or consume them. Suppose you have some XSDs in a jar file and you want to extract them. First, define a custom configuration:

configurations {
    myXSDs
}

Then in your dependencies section, assign the jar file to the configuration and then use the zipTree command to unzip the archive:

task unzipXSDs(type: Copy) {
    from zipTree(configurations.myXSDs.singleFile).matching {
        include '**/*.xsd'
        include '**/*.xjb'
    }
    into "$buildDir/myModel"
}

Printing files in a single zip /jar

For debugging, you might want to print out the contents of a zip or jar file. You can do this by adding a custom task that uses the zipTree forEach method, like this:

task printJar {
    doLast {
        println "Printing jar files"
         zipTree('/path/to/jar/my.jar').forEach(f -> println f)
    }
}

For the Gradle docs on file, see:

https://docs.gradle.org/current/userguide/working_with_files.html

The FileCollection and FileTree classes both have good JavaDocs:

FileCollection

FileTree

Some of my other posts on Gradle:

Dependencies and configurations in Gradle

Gradle incremental tasks and builds

Gradle Release Plugin

Code coverage with Gradle and Jacoco

This entry was posted in Gradle, Java and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

HTML tags are not allowed.

517,978 Spambots Blocked by Simple Comments