0

I try to create directory using groovy.

But then i run this nothing happened.

Can't figure it out that's is wrong in this code?

def nametest = "try"
def patchPath = "/D/Test"
def fileName = patchPath + "/" + nametest
println fileName

if (!(new File(fileName)).exists()) {
    (new File(fileName)).mkdir()
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

1 Answers1

1

This works:

def nametest = 'try'
def patchPath = '/D/Test'
def fileName = "${patchPath}/${nametest}"

def file = new File(fileName)
if(!file.exists()) {
    // you can check the return value
    // of this call to know if it succeeded
    // if you like...
    file.mkdir()
}
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • Are you wanting to create `/D/Test` too or is it assumed that exists? – Jeff Scott Brown Apr 14 '22 at 13:41
  • Jeff Scott Brown - i assume this path exists – stevemayster Apr 14 '22 at 13:49
  • nope, not working for me – stevemayster Apr 14 '22 at 13:52
  • "nope, not working for me" - Very strange. That is all standard Java API stuff. I am sorry that I cannot help. – Jeff Scott Brown Apr 14 '22 at 14:13
  • 1
    It may be a permission problem. It is impossible to say for sure with what little information is provided. – Jeff Scott Brown Apr 14 '22 at 14:14
  • See https://gist.github.com/jeffbrown/51a0ab45e926f376a77aef95d19d46ae. – Jeff Scott Brown Apr 14 '22 at 14:17
  • thanks you already help me. You right,it's a permission issue. Don't know why groovy don't throw any error about it – stevemayster Apr 14 '22 at 14:32
  • "Don't know why groovy don't throw any error about it" - It is good feedback. I think this is a case where we should honor the contract of the Java method you are invoking which includes returning `"true if and only if the directory was created; false otherwise"`. Groovy could intercept that and turn it into an error, but I think a better idea in this case is to have `mkdir` behave the same when it is called from Groovy as when it is called from Java. – Jeff Scott Brown Apr 14 '22 at 16:15
  • @stevemayster "Don't know why groovy don't throw any error about it" - Groovy dispatch is malleable and allows you to have that behavior if you want. There are a number of ways to do it. See the project at https://github.com/jeffbrown/stevemaystermkdir. The comments at https://github.com/jeffbrown/stevemaystermkdir/blob/36cdc59fd8aa3c930d5643f68d0bf444a7f33ccc/app/src/main/groovy/stevemaystermkdir/App.groovy explain what is going on. If you clone that repo and run `./gradlew run` you will see the exception thrown. – Jeff Scott Brown Apr 14 '22 at 20:41
  • https://gist.github.com/jeffbrown/cc41714a4df0ea0f0692866d696fd5a4 – Jeff Scott Brown Apr 14 '22 at 20:43