This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Determine the absolute path of a jar file in classpath Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Determine the absolute path of a jar file in classpath" Watch "Determine the absolute path of a jar file in classpath" New topic
Author

Determine the absolute path of a jar file in classpath

Arun R. S. Chandran
Ranch Hand

Joined: Oct 08, 2008
Posts: 81
hi,

Is there any way to determine the absolute path of jar file within the class path. If anybody knows, Please tell me how to do this?

Thanks,
Arun
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

You can get the classpath like this:



"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

Officially you can't, but a few hacks can help you out. One of them uses ProtectionDomain, search Javaworld.com for the article. The other one uses the fact that with most class loaders you can use the .class file itself as a resource. For instance, try this:
If the class file is located in a JAR file cut off the leading "jar:" and everything after the !. What remains is a URL to the JAR file. If the class file is located in a folder cut off the full class name with / instead of . (e.g. java/lang/String.class).

To convert the remaining URL to a File the following code can help you:
That will only work if the remainingString is a URL with protocol "file".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Zon Horn
Greenhorn

Joined: Dec 11, 2011
Posts: 4
Here's upgrade to other comments, that seem to me incomplete for the specifics of:
- using a relative "folder" outside .jar file (in the jar's same location).
 
Consider Paul's rocket mass heater.
 
subject: Determine the absolute path of a jar file in classpath