get path to groovy source file at runtime
Asked Answered
R

1

6

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

Riverside answered 14/8, 2012 at 18:8 Comment(2)
possible duplicate of How do you get the path of the running script in groovy?Shayna
Does this answer your question? How do you get the path of the running script in groovy?Castellatus
S
20

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)
Shanta answered 14/8, 2012 at 18:28 Comment(4)
... hm, File(".").absolutePath gives me "C:\Users\userNameHere\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Groovy\." and workaround does not work either, bummer :-(Riverside
Aren't you running groovy through cmd?Shanta
goovy console, would that make a difference?Riverside
I run it through my shell, and not groovyconsole, maybe that is the problem: it ends up getting the path to groovyconsole instead of the scriptShanta

© 2022 - 2024 — McMap. All rights reserved.