Gradle : How to load and read a file in gradle task

How to read 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

Read More

No comments :

Post a Comment