简体   繁体   English

如何在Java中双击或执行该路径以获取正确的路径?

[英]How can i get the correct path where it was double clicked or executed from in Java?

My java jar is installed in c:\\program files<i do not know>\\i do not know\\here.jar . 我的Java jar安装在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. 我总是得到c:\\ uesrs \\\\ here.jar及其失败。

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) 试试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) 试试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

You can get the current directory like that: 您可以像这样获取当前目录:

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

What you get using "user.dir" is the user directory. 使用“ user.dir”获得的是用户目录。

Using user.dir will always give you the Users directory in Windows. 使用user.dir将始终为您提供Windows中的Users目录。

Try this: 尝试这个:

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

The "user.dir" system property will return the working directory for the JAR file. 系统属性“ user.dir”将返回JAR文件的工作目录。 The same is true for Binyamin's answer. Binyamin的答案也是如此。

You are looking for the directory that contains the executing JAR file. 您正在寻找包含执行JAR文件的目录。 A similar question was posed in this thread , the answer may help you. 这个线程中也提出了类似的问题,答案可能会对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM