Trying to run task based on existence of a file or not


(Ken Joyner) #1

I am trying to run a task based on the existence of a file (if it doesn’t exist, I want to run the tasks). I have the following:

task init_file() {
  outputs.file file("init.txt")
  doLast {
    File initFile = new File("init.txt")
  }
}

task test(dependsOn: init_file) {
  println "Test"
}

When I run gradle, it always shows as up-to-date even when the file doesn’t exist. What am I doing wrong?

Thanks,

– Ken


(Sterling Greene) #2

A few things…

init_file looks OK. You’re registering an output correctly and you’re doing work in a doLast; however, File initFile = new File("init.txt") isn’t enough to create a file.

So what probably happened, the first time you ran the build, Gradle recorded that the correct state of init.txt after running init_file is to not exist. Since the file doesn’t exist, the task is up-to-date.

You shouldn’t use new File("init.txt") since it will try to create a file relative to the current working directory of the JVM (which might not be in your project directory). You can use file("init.txt") like you used before (it returns a File too).

If you change your task to…

task init_file() {
  outputs.file file("init.txt")
  doLast {
    def initFile = file("init.txt")
    file.text = """
    some content
"""
  }
}

And then run Gradle with --rerun-tasks, that’ll force the task to re-run and it should behave properly after that (deleting init.txt will cause the task to run again).


(Ken Joyner) #3

Thanks, that did work. Did not realize new File(“init.txt”) was relative to the JVM working directory.