Posted By:
Brian_Sullivan
Posted On:
Wednesday, March 21, 2001 05:56 PM
It's better to put your classes _and_ your resources in the
same .jar file, and then not bother with any of this.
But for completeness, it is possible, so long as all
your classes are loaded from an application standard
class loader. (If loaded over the net, through a custom
classloader, etc. then it's another matter.)
This will get the directory for your classes if running from
a class, not a jar.
You know your own package name. If not, getClass() on an instance,
or YourClassName.class will get it; convert it to a String, and
replace all the .'s by File.separator. Add '.class'.
So com.mycorp.myfile is com/mycorp/myfile.class or
commycorpmyfile.class. This is the end of the filename
to check.
Now, get the java.class.path System Property. Parse it
out according to the path separator for the platform. This
is the front of the filename to check.
Form a filename from each path portion combined with the
File.separator and the class name from above; if that file exists
using (new File(filename)).exists(), then that's your directory.
For efficiency, skip class parts ending in .jar or .zip.
If you really want to go all out, search each .jar or .zip in
turn for the .class as well; that would then be completely
generalized.
Is there a way to use the ClassLoader itself for this information?