Search code examples
javaeclipsejargetresource

getResourceAsStream in dynamically loaded jar


I kow there are dozens (if not hundreds) questions about Java's getResource/getResourceAsStream but i did not find any answers to my problem.

I load jars dynamically with: (String path is given)

File jar = new File(path);
URL url = new URL("file", "localhost", jar.getAbsolutePath());
URLClassLoader loader = new URLClassLoader(new URL[] { url });
c = loader.loadClass(name);

Then within the jar i try to load a resource in the jar. This resource clearly exists in the jar and the whole procedure works if I just run the whole thing with a class loader in Eclipse. In a jar it does not work.$

getClass().getResourceAsStream("resource.dat"); 

I tried every possible combination of /packageName/resource.dat, packageName/resource.dat, /resource.dat and resource.dat. They all throw a stream closed Exception.

The I tried debugging and ended up printing the URL of these files loaded via getClass().getResource(path)

This led to following URL and it does not look normal to me. Is it supposed to say "localhostC:..."?

jar:file://localhostC:\Users\******\export.jar!/packageName/resource.dat

Converting this URL also throws an Exception (URISyntaxException).

Is this URL really broken or am I just doing something wrong?


Solution

  • Try changing the line:

    URL url = new URL("file", "localhost", jar.getAbsolutePath());
    

    to

    URL url = new URL("file", null, jar.getAbsolutePath());
    

    The host parameter in the URL constructor is not applicable in this case.