Java: Finding your programs directory

Status
You're currently viewing only gumbo's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

gumbo

Ars Tribunus Angusticlavius
6,107
I found this method off usenet:

From Chris Smith:

If you want the current working directory, then
System.getProperty("user.dir") will do. However, I don't think that's what
you want. You want the directory containing your program code. That's a
bit more difficult.

One thing you can try is this:

1. Pick any class that's definitely part of your application, and get its
Class object. This can be done, for example, with:

Class theClass = MyAppClass.class;

2. Get the class's ProtectionDomain, and the ProtectionDomain's CodeSource:

ProtectionDomain pDomain = theClass.getProtectionDomain();
CodeSource codeSource = pDomain.getCodeSource();

3. The docs state that the CodeSource may be null. If it is, then give up:

if (codeSource == null) throw new CannotFindDirException();

4. Get the location of the code source. This conveniently returns a URL,
relative to which you can build your URL for the HTML reference.

URL loc = codeSource.getLocation();

HTH,
Chris Smith

Works for we, whereas the previous version did not. I think that version need the class on the classpath, while this one doesn't.

gubmo
 
Status
You're currently viewing only gumbo's posts. Click here to go back to viewing the entire thread.
Not open for further replies.