Search code examples
javajarclassloader

How to load resources from other JAR file


I have troubles to make loading resources from other jars running. Here is the setup I have

resource.jar  # contains resources I want to load
`-res/hwview/file1

engine.jar    # my application which need resources
`-res/hwview/file2

Interesting thing is that using the code below I'm able to load file2 (which is in the jar I run) but not the file1.

String dir = "res/hwview";
Enumeration<URL> e = getClass().getClassLoader().getResources(dir);
while(e.hasMoreElements()) {
    // prints only file1 from engine.jar 
    // (actually it's in classes directory because I run it from my IDE)
    System.out.println(e.nextElement());
}

[OUTPUT]
/path/to/my/project/SiHwViewUiModel/classes/res/hwview

So I thought maybe the jar was not picked up by the ClassLoader so I printed what was loaded

ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
    System.out.println(url.getFile());
}

[OUTPUT]
/path/to/my/project/SiHwViewUiModel/classes/
/path/to/my/project/Resources/deploy/resources.jar
... and other not so important jars

Any ideas? Thanks for any help!


Solution

  • I found the solution. The problem with getResources() method and similar is that thay cannot be given a directory but only a particular file. This means that if I want to search in the whole classpath for a particular structure I need to create marker file in base directories.

    Example: I want to get to my/path directory -> create marker.info (name does not matter) file and then search for it.

    resources.jar
    `- my/path/
       |- my/directories
       `- marker.info
    
    resources2.jar
    `- my/path/
       |- my/other/directories
       `- marker.info
    
    # search
    Enumeration<URL> urls = getClass().getClassLoader().getResources("my/path/marker.info"); 
    
    # print
    print(urls);
    /path/to/resources.jar!/my/path/marker.info
    /path/to/resources2.jar!/my/path/marker.info