73

Is there any way to determine current filesystem location of executed class from the code of this class, in runtime, given that it's executed using java command?

For example for following class:

public class MyClass{
 public static void main(String[] args){\
   new MyClass().doStuff();
 }

 private void doStufF(){
   String path = ... // what to do here?!
   System.out.println("Path of class being invoked: " + path);
 }

}

Is there any way to get and print the correct path in filesystem of MyClass.class file just being invoked?

Similarly, if I invoke jar file from java -jar command, is there any way to get a path of jar file from within classes inside that jar?

P.S.:Please, do not make any assumptions about working directory from which java command is invoked!

Piotr Sobczyk
  • 6,443
  • 7
  • 47
  • 70

1 Answers1

118

The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the parent to find the directory that the .jar is in.

  • 7
    Beware when doing this: if your class file is somewhere in a directory that has a space in it, the returned string (which is the path part of a URL, which getLocation() returns, and is therefore URL encoded) will contain '%20' instead of spaces! – Jan de Vos Nov 02 '16 at 15:31
  • 2
    @JandeVos Using the `File(java.net.URI)` constructor seems to fix that issue. – Spooky May 21 '17 at 00:11
  • 1
    @Spooky's comment: so it must be `final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getURI().getPath());` – Andreas Covidiot Mar 08 '18 at 13:42
  • 1
    I am trying this, but it is returning the path of the folder where I ran the command instead of the subfolder with the class file. – Spencer Williams Sep 07 '20 at 16:46