artjomka artjomka - 1 year ago 269
Groovy Question

Groovy resource from classpath not loaded

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)

resource == null

I tried debugging and in Expression Evaluation windows this code
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
, but in Expression Evaluation window classloader was
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 ?


Changed the way resource file was parsed. When
- full path to file this works, but if
is just file name and that file in classpath then
resource == null


Change the way resource file loaded, clean up dependencies bit and all is working, I guess yesterday just wasn't my day.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download