views:

8375

answers:

2

My code runs inside a jar file, say foo.jar, and I need to know, in the code, in which folder the running foo.jar is.

So, if foo.jar is in C:\FOO\, I want to get that path no matter what my current working directory is.

+1  A: 

Use ClassLoader.getResource() to find the URL for your current class.

For example:

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

(This example taken from a similar question.)

To find the directory, you'd then need to take apart the URL manually. See the JarClassLoader tutorial for the format of a jar URL.

Jon Skeet
My JAR file is obfuscated, so this answer does not solve my problem. But I haven't specified that in the question, so this is still a valid answer.
Morgaelyn
If it's obfuscated, use Test.class.getName() and do appropriate munging.
Jon Skeet
+6  A: 
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

Obviously, this will do odd things if you class was loaded from a non-file location.

Zarkonnen
In order for this answer to work, it needed a small modification:return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());PS: This doesn't work in JVMs previous to 1.5.
Morgaelyn