来自classpath的Groovy资源未加载 [英] Groovy resource from classpath not loaded
问题描述
大家好.
我正在使用spock框架在我的groovy项目中进行测试(IDE-Intellij Idea 12.6).我的spock规范类将文件名传递给groovy对象进行处理(该文件肯定在classpath中),但是当我尝试以这种方式获取该文件时
def资源= getClass().getClassloader().getResourceAsStream(文件路径)assert resource!= null:未找到路径$ {filepath}的输入流"def rootNode =新的XmlParser().parse(资源)
然后 resource == null
.
我尝试调试,并且在Expression Evaluation窗口中,此代码 getClass().getResource(fileName)
返回资源.
我试图检查哪种情况的类加载器在第一种情况下(在带有代码的类中)和第二种情况下(表达式评估"窗口)使用.
在第一种情况下,类加载器是 sun.misc.Launcher$AppClassLoader@18dabf1
,但是在表达式评估窗口中,类加载器是 groovy.lang.GroovyClassLoader$InnerLoader@1e69757
这就是我的资源为空的原因.
有人可以指导我做错什么以及如何加载该资源文件吗?
更新:
更改了解析资源文件的方式.当 filepath
-文件的完整路径有效时,但是如果 filepath
只是文件名,而该文件位于classpath中,则 resource == null
>
UPDATE2 :
改变资源文件的加载方式,清理依赖项,一切都正常了,我想昨天不是我的日子.
问题很可能与Spock无关.很难说是什么原因造成的,但是读取资源最安全的方法是 getClass().getClassLoader().getResourceAsStream()
或 Thread.currentThread().getContextClassLoader().getResourceAsStream()
,具体取决于环境.
不确定执行新文件(资源)
时Groovy会做什么,因为没有 File(URL)
构造函数(只有 File(URI))
构造函数).无论如何,应尽可能避免从类路径获取 File
.
Good day everyone.
I am using spock framework for testing in my groovy project(IDE - Intellij Idea 12.6). My spock specification class pass filename to groovy object for processing (that file is in classpath for sure), but when i try to get that file this way
def resource = getClass().getClassloader().getResourceAsStream(filepath)
assert resource != null : "No input stream found for path ${filepath}"
def rootNode = new XmlParser().parse(resource)
Then resource == null
.
I tried debugging and in Expression Evaluation windows this code getClass().getResource(fileName)
returns resource.
I tried to check which classloader used in first case (in class with the code) and in second case (Expression Evaluation window).
In first case classloader was sun.misc.Launcher$AppClassLoader@18dabf1
, but in Expression Evaluation window classloader was groovy.lang.GroovyClassLoader$InnerLoader@1e69757
I suppose that's the reason my resource was null.
Can someone guide me about what I am doing wrong and how can I load that resource file ?
UPDATE:
Changed the way resource file was parsed. When filepath
- full path to file this works, but if filepath
is just file name and that file in classpath then resource == null
UPDATE2:
Change the way resource file loaded, clean up dependencies bit and all is working, I guess yesterday just wasn't my day.
The problem is very likely unrelated to Spock. It's hard to say from a distance what's causing it, but the safest way to read a resource is getClass().getClassLoader().getResourceAsStream()
or Thread.currentThread().getContextClassLoader().getResourceAsStream()
, depending on the environment.
Not sure what Groovy does when you do new File(resource)
, as there is no File(URL)
constructor (only a File(URI)
constructor). In any case, getting a File
from a class path should be avoided whenever possible.
这篇关于来自classpath的Groovy资源未加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!