Search code examples
javaresourcesjarclassloader

Loading resource from a jar in a Web Application


I read all the questions with answers but still it doesn't work for me.

In my web application I have a jar which contains few images and xmls. These are required by the classes in that jar itself. So I modified the required lines as below:

I changed the classes inside my jar to refer the resources(which are present inside the jar itself) by using :

Thread.currentThread().getContextClassLoader().getResource(path) // returns null

I had also tried before :

MyClassName.class.getResource(path) // null again

I read a lot about this and got to know that the later line of code will be able to pick up the resources, but unfortunately neither of it works for me...am I missing something?

Note: Running on Tomcat7 and since I am running on Vista, I get the 'path' value as '\myFolder\images\'

Thanks


Solution

  • There are few points one must take care when loading resources from within a jar, which is embedded in a web application

    1. Loading a file is different than loading a resource. When we use File.seperator it is usually w.r.t Files and absolute paths. It is not recommended for loading resources.
    2. When loading resources from within a jar, make sure you are not using the File.seperator and using the normal '/' as it is relative path w.r.t the jar.
    3. If you are reading properties from an xml within the jar...and that property refers to another location, make sure you are reading it with the '/' slashes. Again, File.seperator will not work for loading resources because it will replace '/' with '\' (windows system)
    4. Finally, when loading resources in your jar code, use the following lines

      MyCurrentClass.class.getResource(path)

    Hope it helps people dealing with xmls within jars in a web application