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.

4
  • Maybe it's throwing NPE because your code is not yet packaged into a JAR file during unit testing? Commented Feb 22, 2012 at 17:16
  • Thanks @yegor256 but I am not uni testing. I am executing the jar itself. Commented Feb 22, 2012 at 17:17
  • You need split the sequence of calls (getClass().getProtectionDomain()...) in multiple lines in order to know what exactly returned null instead of expected instance. Commented Oct 8, 2013 at 18:34
  • @TapasBose how you solved NPE? Commented Jan 4, 2014 at 8:39

2 Answers 2

7

There is a way:

return new File(ClassA.class.getProtectionDomain().getCodeSource().getLocation().toURI().g‌​etPath()); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks I have added a code. But it is throwing NullPointerException
@TapasBose in what case you got NPE can you elaborate and how you solved it?
-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

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.