Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes name of a jar Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "name of a jar" Watch "name of a jar" New topic

name of a jar

Jason Kretzer
Ranch Hand

Joined: May 31, 2001
Posts: 280
I have a jar that needs to perform an operation on itself(like read a text file inside itself). This is easy enough, however, here is the catch. How can a jar determine what its own file name is? This will need to be determined at runtime.
1.) foo.jar is created using the JDK jar tool.
2.) John Q. User renames the jar to bar.jar.
3.) When executed, bar.jar knows its name is "bar.jar" and sets up a connection to do its operation.

Question: How can I get bar.jar to know what its name is at runtime?

Jason R. Kretzer<br />Software Engineer<br />System Administrator<br /><a href="" target="_blank" rel="nofollow"></a>
Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

I guess a solution is not as simple as having only 1 jar file??? If you have only 1, then it would be easy to determine the name of it, with an instance of the File class. But if you have more than 1, hmmmmmm... You could possibly get the instance of the Class you are running, then try to find that class in the jar files. But, if you have the same class in multiple jar files, then that wouldn't work. I do not have a simple solution, but maybe someone else does, or I have jogged your brain a little.
Michael Ernest
High Plains Drifter

Joined: Oct 25, 2000
Posts: 7292

I don't think there is an easy way to do it, but I don't think it matters, either. Your JAR represents a self-contained directory structure, even if it's completely flat. The "document root" of your JAR is the top level directory of all the contained elements. So if your Main-Class knows how to get to the top of the JAR, and can traverse down to the location of the text file, voila! You're good to go.

Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
I agree. Here's the link:
subject: name of a jar
It's not a secret anymore!