Introduction to FileTree in Gradle Api

FileTree is an interface that extends FileCollection and introduces methods like matching() and visit(). It class represents a hierarchy of files in a given directory. It includes files in same folder and all sub folders.

How to get all files in a Directory

File Structure

To load all files in a given directory and its sub directories you can use FileTree. Syntax for FileTree is as shown below.

FileTree tree = fileTree('path/to/dir')

The FileTree can get files in following ways

  1. from relative path
  2. from

We can write a gradle task to list all the files in the src folder as shown below.


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

When we run the aobe task using command gradle -q loadFiles it will give the following output

sample1.txt
sample2txt
file1.properties
A.java

Read More

Introduction to FileTree in Gradle Api

FileTree is an interface that extends FileCollection and introduces methods like matching() and visit(). It class represents a hierarchy of files in a given directory. It includes files in same folder and all sub folders.

How to get all files in a Directory

File Structure

To load all files in a given directory and its sub directories you can use FileTree. Syntax for FileTree is as shown below.

FileTree tree = fileTree('path/to/dir')

The FileTree can get files in following ways

  1. from relative path
  2. from

We can write a gradle task to list all the files in the src folder as shown below.


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

When we run the aobe task using command gradle -q loadFiles it will give the following output

sample1.txt
sample2txt
file1.properties
A.java

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.

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.

How to load a file in Gradle Task

To load a file, you can take following three approaches

  1. Load file using relative path
    File file = file('relative/path/file')
    
  2. Load file using absolute path
    File file = file('absolute/path/file')
    
  3. Load a file using File object
    File file = file(new File('somePath'))
    

Lets see how these three approaches work

task loadFiles << {
   println file('src/main/resources/file1.properties')
   println file('/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties')
   println file(new File('src/main/resources/file1.properties'))

}

When we run the above task using command gradle -q loadFiles it will give the following output

/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties
/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties
/home/ekiras/workspace/tutorials/gradle/src/main/resources/file1.properties

How to read a File in gradle task

Say, we have a file sample.txt in src/main/resources folder with the following context

I am some awesome text line 1
I am some awesome text line 2

Lets read this file in a gradle task.

task readFile(){
    doLast{
        File file = file('src/main/resources/sample.txt')
        println file.text
        println ""
        file.readLines().each{
            println it
        }

    }
}

Now when we run the command gradle -q readFile we will get the following output.

I am some awesome text line 1
I am some awesome text line 2

I am some awesome text line 1
I am some awesome text line 2

How to check if the operation system is Windows, Linux or Mac Os.

org.gradle.internal.os.OperatingSystem is an interface in gradle. This interface provides methods to get th einformation about the operating system.

This interface provides the following method to get the information about the operating system.

task osInfo(){
    doLast{
        println OperatingSystem.current();
        println OperatingSystem.current().name;
        println OperatingSystem.current().isLinux();
        println OperatingSystem.current().isMacOsX();
        println OperatingSystem.current().isWindows();
    }
}

When we run the task with the command gradle -q osInfo it will give the following information.

:osInfo
Linux 4.4.0-51-generic amd64
Linux
true
false
false

BUILD SUCCESSFUL

Total time: 0.68 secs

Gradle Build Lifecycle Phases

A gradle build has three phases

  1. Initialization - In this phase the gradle build is initialized. Gradle scans the project and its sub projects to create a Project instance of each project and sub project.
  2. Configuration - In this phase the gradle build is configured. In this phase a Task tree is created which determines how and when to run the tasks.
  3. Execution - In this phase the gradle build is executed. This phase actually runs the tasks configured in the configuration phase.

What are the Gradle Build Phases

Lets take the following example

build.gradle


println 'This is executed during the configuration phase.'

task configured {
    println 'This is also executed during the configuration phase.'
}

task test {
    doLast {
        println 'This is executed during the execution phase.'
    }
}

task testBoth {
    doFirst {
      println 'This is executed first during the execution phase.'
    }
    doLast {
      println 'This is executed last during the execution phase.'
    }
    println 'This is executed during the configuration phase as well.'
}

The above example is self explanatory and tell you about the gradle build lifecycle phases. When run it will give the following output.

This is executed during the initialization phase.
This is executed during the configuration phase.
This is also executed during the configuration phase.
This is executed during the configuration phase as well.
:test
This is executed during the execution phase.
:testBoth
This is executed first during the execution phase.
This is executed last during the execution phase.

BUILD SUCCESSFUL

Total time: 1 secs

Also Read

How to write a Gradle Task

A gradle task can be written in the following two ways

task hello(){
  doLast(){
    println "Hello World"
  }
}

Or you can write a task as follows

task hello << {
   println "Hello World"

}

Here in example 2, << operator is simply an alias for doLast.

Write a Gradle Task that depends on another Gadle Task

Lets take an example of the following gradle file.

build.gradle

task openFile(){
    doLast{
        println "Open file"
    }
}

task readFile(dependsOn : 'openFile'){
    doLast{
        println "Read File"
    }
}

task closeFile(dependsOn : ['openFile','readFile']){
    doLast{
        println "Close File"
    }
}

Here in this example, we have three tasks

  1. openFile - that will open a file
  2. readFile - that will read a file
  3. closeFile - that will close a file.

Now, for able to read from a file, we should first open a file, so readFile depends on openFile, also a file will be closed after reading a file so closeFile task depends on both openFile and readFile

Now if we run the tasks, it will give the following outputs

> gradle -q openFile or gradle -q oF
> Open file

> gradle -q readFile or gradle -q cF
> Open file
> Read File

gradle -q closeFile or gradle -q cF
> Open file
> Read File
> Close File

A gradle task is loaded in a lazy manner that means you can define a task anywhere in the build file. The task dependency is looked in execution phase and not in configuration phase.

Let's check it by the following example


// Task B does not exists here but will be resolved at runtime.
task A(dependsOn : 'B'){ 
  doLast(){
    println "A"
  }
}

task B(){
  doLast(){
    println "B"
  }
}


Also Read