Greg Ofiesh wrote:
Dear news group friends,
I am new to Java, only been working with it for a month or so. Here is
my problem:
I need to package my tree of classes into a Jar file. One of those
classes must be able to determine at run time what Jar file it came
from, and more importantly where that Jar file is located at. This is
because it must pass the Jar file path and file name to another class
that searches the Jar file for a data file located in the root folder
in the Jar file.
Does anyone know an easy way to have a class find the location of the
Jar file it came from? Any help would be wonderful.
Greg Ofiesh
Greg,
Assuming you are using the default class loader and not anything funky
(a J2EE environment would probably qualify as "funky"), you could use
the Class.getResource() method to get the URL for the class file:
// Start ResourceExample.java
public class ResourceExample
{
public static void main(String args[])
{
System.out.println(ResourceExample.class.getResour ce(
"ResourceExample.class"));
}
}
// End ResourceExample.java
# Start example output
[tmp]$ java -cp . ResourceExample
file:/tmp/ResourceExample.class
[tmp]$ jar cvfm re.jar re.mf ResourceExample.class
added manifest
adding: ResourceExample.class(in = 937) (out= 533)(deflated 43%)
[tmp]$ java -jar re.jar
jar:file:/tmp/re.jar!/ResourceExample.class
# End example output
Of course, after rereading your original post, you may be able to do
this by just using ClassLoader.getResource() directly in your second
class. For example, if you needed "xyz.txt" from the jar file you could do
URL res = this.getClass().getClassLoader().getResource("/xyz.txt");
The only potential issue is if you have multiple "xyz.txt" files in the
CLASSPATH.
HTH,
Ray
--
XML is the programmer's duct tape.