@H_502_3@
我需要在运行时检索Groovy 2.3中脚本文件的完整路径.
实际上我遇到的问题与这里描述的问题相同: get path to groovy source file at runtime.
实际上我遇到的问题与这里描述的问题相同: get path to groovy source file at runtime.
我的脚本可以从GroovyShell执行或不执行.
我的脚本位于:
C:\users\myname\documents\scripts\myscript.groovy
=>我想在运行时检索此路径.
如果我使用被接受的解决方案:
println new File(".").absolutePath
我得到的实际上是:
C:\groovy-2.3.7\.
这是groovy主文件夹.这是不正确的.
另一个提议的答案是:
URL scriptUrl = getClass().classLoader.resourceLoader.loadGroovySource(getClass().name)
仅当我的脚本在类路径中时,或者在groovy-starter.conf中使用load指令在groovy启动时加载它时才有效.否则返回null.我可以使用这种方法,但它并不令人满意,因为它就像传递参数一样,这里的目标是用户能够从任何地方执行脚本而无需修改或配置.
我也对这个专注于这个问题的JIRA感兴趣:
JIRA-1642
解决方案似乎使用为此目的创建的@SourceURI注释.问题是我无法使其发挥作用.我尝试执行以下所示的代码用法:SourceURI
@groovy.transform.SourceURI def sourceURI assert sourceURI instanceof java.net.URI path = sourceURI.toString() println "path = $path"
我得到的是(groovy 2.3.7)不是路径而是源代码:
path = data:,@groovy.transform.SourceURI%20def%20sourceURI%0A%0A%20assert%20sourceURI%20instanceof%20java.net.URI%0Apath%20=%20sourceURI.toString()%0Aprintln%20%22path%20=%20$path%22
如何使用@SourceURI注释来检索脚本文件的路径?
解决方法
我一直在寻找与您相同的脚本路径信息.我注意到通过shell运行以下代码时:
@groovy.transform.SourceURI def sourceURI assert sourceURI instanceof java.net.URI sourceURI.properties.each { i -> println i }
我得到以下有用的结果(注意路径中的值):
rawAuthority=null opaque=false scheme=file rawQuery=null port=-1 rawUserInfo=null path=/home/ttresans/GroovyScripts/TestSourceURI.groovy class=class java.net.URI absolute=true schemeSpecificPart=/home/ttresans/GroovyScripts/TestSourceURI.groovy rawPath=/home/ttresans/GroovyScripts/TestSourceURI.groovy query=null fragment=null host=null authority=null rawFragment=null userInfo=null rawSchemeSpecificPart=/home/ttresans/GroovyScripts/TestSourceURI.groovy
但是,如果我将相同的东西粘贴到GroovyConsole中,我会得到以下内容:
rawAuthority=null opaque=true scheme=data rawQuery=null port=-1 rawUserInfo=null path=null class=class java.net.URI absolute=true schemeSpecificPart=,@groovy.transform.SourceURI def sourceURI assert sourceURI instanceof java.net.URI sourceURI.properties.each { i -> println i } rawPath=null query=null fragment=null host=null authority=null rawFragment=null userInfo=null rawSchemeSpecificPart=,@groovy.transform.SourceURI%20def%20sourceURI%0Aassert%20sourceURI%20instanceof%20java.net.URI%0AsourceURI.properties.each%20%7B%20i%20-%3E%20%0A%20%20%20%20println%20i%0A%7D%0A
这是在Ubuntu上的Groovy 2.3.9上.
所以看起来GroovyConsole的启动可能是一个问题,但注释确实产生了所需的路径.
@H_502_3@