When using Class.getResource()
and supplying a rather common resource name, like "license.html"
, Java may load a "license.html"
resource from another JAR file which is listed earlier in the CLASSPATH, but may be completely unrelated to my application. Is there a way to force the ClassLoader to first try to load the resource from the same JAR file which my class is in and only if not found, look in other JARs on the CLASSPATH?
Asked
Active
Viewed 2,172 times
4
-
6*'common resource name, like `"license.html"`'* A Good reason to give it an uncommon path, like `"com/our/app/license.html"`. – Andrew Thompson May 08 '12 at 13:31
-
Your resources should be named in a way that makes them unambiguous - meaning that if there's a match in another `ClassLoader`, it should be considered. Then you'd `getResources()` to list all such matches. – Romain May 08 '12 at 13:31
-
1+1 to Andrew; think of it the same way as package naming. – Dave Newton May 08 '12 at 13:32
-
If you need to keep the file on the default package you may try to ask for the classloader of a class that is in that jar file. – Juan Alberto López Cavallotti May 08 '12 at 13:36
-
@Juan Yes, I have that class. Anyway, MyClass.class.getResource() may load the wrong resource. – mstrap May 08 '12 at 13:37
2 Answers
4
Alternatively you could use the JarURLConnection if you know the exact jar in which your file resides:
jar:<url>!/{entry}

Edwin Dalorzo
- 76,803
- 25
- 144
- 205
-
-
@mstrap If you know the exact jar file in which your license.html file resides this should work, otherwise, back to square one. – Edwin Dalorzo May 08 '12 at 13:36
-
2`URL urlToClass = obj.getClass().getProtectionDomain().getCodeSource().getLocation();` Note: Requires trust/no security manager, and for applets and JWS, will point back to the server even if cached. – Andrew Thompson May 08 '12 at 13:38
-
1..but note the edit to that comment. ;) I still feel you should go for 'specific path according to package name'. – Andrew Thompson May 08 '12 at 13:41
3
..common resource name, like "license.html"'
A good reason to give it an uncommon path, for instance according to the package
name.
E.G. "/com/our/app/license.html"
is unlikely to collide with any other license.html

Andrew Thompson
- 168,117
- 40
- 217
- 433