GetResourceAsStream in a dynamically loading jar

I have dozens (if not hundreds) of Java questions about getResource / getResourceAsStream, but I have not found the answers to my problems.

I load jars dynamically using: ( String path)

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 in jar I try to load the resource in the bank. This resource clearly exists in the bank, and the whole procedure works if I just start it all with the class loader in Eclipse. This does not work in the bank. $

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

I have tried all the possible combinations /packageName/resource.dat, packageName/resource.dat, /resource.datand resource.dat. They all throw an exception stream closed.

I tried debugging and ended up typing the URL of these files downloaded via getClass().getResource(path)

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

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

URL- (URISyntaxException).

URL- - ?

+4
2

:

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

to

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

URL .

+2

-, File toURI(), URL-, :

URL url = new File(path).toURI().toURL();

, , :

File jar = new File(path);
URLClassLoader loader = new URLClassLoader(new URL[] { jar.toURI().toURL() });

, jar, Class, jar, , Class c:

Class<?> c = loader.loadClass(classPathAndName);
URL resource = c.getResource("data.txt");

- :

jar:file:/C:/test/testjar.jar!/testpkg/data.txt

ClassLoader, , :

loader.getResoure(packageAndResourceName);

, javadoc:

; null , . findResource(String), .

+2

All Articles