Skip to main content

Gradle : What is a FileCollection in Gradle Api

Introduction to FileCollection

FileCollection is an interface that extends Iterable<File>, AntBuilderAware and Buildable interfaces.

How to load files in a FileCollection

Suppose we have a file structure as shown in image below

File Structure

We can load multiple files for operation using the following syntax

FileCollection collection = files('relative/path/file1','absolute/path/file2',new File('file3'))

As shown in the example above we can load files in three ways

  1. From a relative path
  2. From a absolute path
  3. From a File object.

We can write a gradle task to read all files in a folder or directory as follows

task fileTree(){
doLast{
FileTree tree = fileTree('src')
tree.each {
println it.name
}
}
}

Now when we run the above gradle task with the command gradle -q fileTree, it will give the following output

sample1.txt
sample2txt
file1.properties
resources.tar.gz
resources.jar
resources.zip
A.java

Operations and methods available for FileCollection

  1. getSingleFile() - It returns a single file. (it will throw IllegalStateException if files contains more than one file or no file)
  2. getAsFileTree() - It returns the FileCollection as a FileTree.
  3. plus(FileCollection collection) - It will add the specified file collection to the existing file collection.
  4. minus(FileCollection collection) - It will remove from the collection files in specified collection.
  5. filter(Closure filter) - It will filter the files from collection and make changes to the same collection.

Read More

Comments