groovygroovy-console

get path to groovy source file at runtime


Given the following directory structure:

/home/some/random/foler/myScript.grooy

... how can I programmatically obtain the path to myScript.grooy parent directory right in the script itself?

Ultimately I'm trying to read in several files from the same directory the script is in.

EDIT: trying to run it on Windows 7, Groovy 2.0.1, groovy console


Solution

  • Well, the solution is in Java's File class:

    println new File(".").absolutePath
    

    If you want to obtain every groovy script in the same directory, maybe you could use some of other facilities in the Groovy JDK, like eachFile:

    def files = []
    new File(".").eachFile { 
        if (it.name.endsWith(".groovy") ) files << it 
    }
    println files
    

    If you want the running script name, well, you've got a problem (https://issues.apache.org/jira/browse/GROOVY-1642)

    Accordingly to that JIRA, this is the current workaround (which doesn't always work):

    URL scriptUrl = getClass().classLoader.resourceLoader
        .loadGroovySource(getClass().name)