0

Is there any way by which we can find the current location from where the jar is forked, programmatically? Say I am executing a Jar from D:/Jars/myjar.jar, so can I get that path from the code?


@AljoshaBre I tried this

try {
        File file = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        System.out.println(file.getAbsolutePath());
    } catch (Exception e1) {

        e1.printStackTrace();
    } 

Is throwing NPE. :(

But

System.out.println(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

is showing client.jar only. Not the absolute path. It is inside a Jar.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

2 Answers2

7

There is a way:

return new File(ClassA.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath());
nullpotent
  • 9,162
  • 1
  • 31
  • 42
-4

If you execute it as java -jar D:/Jars/myjar.jar if you do

new File("afile").getAbsolutePath();

it will return D:/Jars/afile and the you can just do a substring.

The new File create the file from the folder which the jar is, so if you import this JAR in an application this method doesn't work.

Sorry I've just tried...it isn't true :P it return the path of where you called the 'java' command

rascio
  • 8,968
  • 19
  • 68
  • 108
  • Thanks, If I execute from cmd `java -jar "C:\Users\Tanmoy\Desktop\Movie Library.jar"` then `System.out.println(new File("afile").getAbsolutePath());` prints `C:\Users\Tanmoy\afile` but without `Desktop` how can I substring? – Tapas Bose Feb 22 '12 at 17:28