0

My java jar is installed in c:\program files<i do not know>\i do not know\here.jar. When the user execute my application.

I always get c:\uesrs\\here.jar and its failing.

String Windows7HomeEditionProgramFileDirectroyStruct = System.getProperty("user.dir");

How can i get the correct path where it was double clicked or executed from?

Details (tested both answer but none is saying where the jar is located):

Try 1)

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

new File(".").getCanonicalPath();

C:\Users\sun>java -jar "C:\Users\sun\Documents\NetBeansProjects\JavaApplication1
\dist\JavaApplication1.jar"
C:\Users\sun\.

Try 2)

ClassLoader.getSystemClassLoader().getResource(".").getPath();

C:\Users\sun>java -jar "C:\Users\sun\Documents\NetBeansProjects\JavaApplication1
\dist\JavaApplication1.jar"
Exception in thread "main" java.lang.NullPointerException
        at javaapplication1.JavaApplication1.main(JavaApplication1.java:18)

Follow up:

String test = JavaApplication1.class.getProtectionDomain().getCodeSource().getLocation().getPath();

C:\>java -jar "C:\Users\sun\Documents\NetBeansProjects\JavaApplication1\dist\Jav
aApplication1.jar"
/C:/Users/sun/Documents/NetBeansProjects/JavaApplication1/dist/JavaApplication1.
jar

3 Answers3

2

You can get the current directory like that:

String path = new File(".").getAbsolutePath();

What you get using "user.dir" is the user directory.

MByD
  • 135,866
  • 28
  • 264
  • 277
  • How do i get the result output: "C:\Users\sun\Documents\NetBeansProjects\JavaApplication1 \dist\"? The location where it is, but not the user location or from where it was command. –  Mar 03 '12 at 12:27
  • User took the jar file and he placed it C:\here.jar, tomorrow he took the file and placed it in D:\here.jar. Now when he launch from command prompt as C:\java -jar d:'\here.jar , i would like to get the output result as not c:\ but d:\. Any idea how? –  Mar 03 '12 at 12:38
2

Using user.dir will always give you the Users directory in Windows.

Try this:

ClassLoader.getSystemClassLoader().getResource(".").getPath();
mohdajami
  • 9,604
  • 3
  • 32
  • 53
1

The "user.dir" system property will return the working directory for the JAR file. The same is true for Binyamin's answer.

You are looking for the directory that contains the executing JAR file. A similar question was posed in this thread, the answer may help you.

Community
  • 1
  • 1
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254