mdp mdp - 1 year ago 64
Java Question

Access a resource outside a jar from the jar

I'm trying to access a resource from a jar file. The resource is located in the same directory where is the jar.


I tried different things including the following, but every time the input stream is null:


String path = new File(".").getAbsolutePath();
InputStream inputStream = this.getClass().getResourceAsStream(path.replace("\\.", "\\") + "test.jpg");


File f = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
InputStream inputStream = this.getClass().getResourceAsStream(f.getParent() + "test.jpg");

Can you give me some hints? Thanks.

Answer Source

If you are sure, that your application's current folder is the folder of the jar, you can simply call InputStream f = new FileInputStream("test.jpg");

The getResource methods will load stuff using the classloader, not through filesystem. This is why your approach (1) failed.

If the folder containing your *.jar and image file is in the classpath, you can get the image resource as if it was on the default-package:


Beware: The image is now loaded in the classloader, and as long as the application runs, the image is not unloaded and served from memory if you load it again.

If the path containing the jar file is not given in the classpath, your approach to get the jarfile path is good. But then simply access the file directly through the URI, by opening a stream on it:

URL u = this.getClass().getProtectionDomain().getCodeSource().getLocation();
// u2 is the url derived from the codesource location
InputStream s = u2.openStream();