get path to groovy source file at runtime

删除回忆录丶 提交于 2019-12-11 03:07:30

问题


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


回答1:


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 (http://jira.codehaus.org/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)


来源:https://stackoverflow.com/questions/11958185/get-path-to-groovy-source-file-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!