Java: Finding your programs directory

Status
Not open for further replies.
I'm making a small java program that hopefully one day will be installed on peoples computers but atm I have one small hitch that has me stumped. There seems to be no easy way of finding the directory that my program resides in.

Here is the output of some of my stubs
Code:
System.out.println("user dir= "+System.getProperty("user.dir","aRGH!"));
outputs: "user dir= C:\java\forte4j\bin"

System.out.println("user home= "+System.getProperty("user.home","aRGH!"));
outputs: "user home= C:\Documents and Settings\Surgeon"

And if I create a file in the current directory it ends up in the wrong place.
Code:
File currentdir = new File("x.y");
System.out.println("current dir= "+currentdir.getAbsolutePath());
outputs: "current dir= C:\java\forte4j\bin\"

Now is this Forte just being a bitch or does every java program think the current directory is \bin?
How can I get around this. I dont really want to have to hardwire paths in. I would like to be able to just put the JAR file in a directory and run it one day.
 

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
Not open for further replies.