Search code examples
groovyjarclassloadergetresource

How to getResource from jar with compiled groovy classes?


I have the groovy script. I compiled it with groovyc and jar'ed classes. So script1.class is in jar's root. And I put some file foo.bar in jas's root too. How do I get that file with getResource? Which ClassLoader should I use? And how do I get this ClassLoader?


Solution

  • Use a groovy class which exists in the same package where the resource is placed.

    def path = 'foo.txt'
    def inputStream = Script1.class.getResourceAsStream(path)
    

    The sample code above, allows you to access the file named foo.txt which is placed in the same package in which Script.class exists. You need to manipulate the stream as per your need.