get path to groovy source file at runtime

vector picture vector · Aug 14, 2012 · Viewed 28.5k times · Source

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

Answer

Will picture Will · Aug 14, 2012

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)