Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

language agnostic - Get the application's path

I've recently searched how I could get the application's directory in Java. I've finally found the answer but I've needed surprisingly long because searching for such a generic term isn't easy. I think it would be a good idea to compile a list of how to achieve this in multiple languages.

Feel free to up/downvote if you (don't) like the idea and please contribute if you like it.

Clarification:

There's a fine distinction between the directory that contains the executable file and the current working directory (given by pwd under Unix). I was originally interested in the former but feel free to post methods for determining the latter as well (clarifying which one you mean).

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Java the calls

System.getProperty("user.dir")

and

new java.io.File(".").getAbsolutePath();

return the current working directory.

The call to

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();

returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that yielded the current class if you're running directly from the filesystem.

Example:

  1. Your application is located at

     C:MyJar.jar
    
  2. Open the shell (cmd.exe) and cd to C:estsubdirectory.

  3. Start the application using the command java -jar C:MyJar.jar.

  4. The first two calls return 'C:estsubdirectory'; the third call returns 'C:MyJar.jar'.

When running from a filesystem rather than a JAR file, the result will be the path to the root of the generated class files, for instance

c:eclipseworkspacesYourProjectin

The path does not include the package directories for the generated class files.

A complete example to get the application directory without .jar file name, or the corresponding path to the class files if running directly from the filesystem (e.g. when debugging):

String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

if (applicationDir.endsWith(".jar"))
{
    applicationDir = new File(applicationDir).getParent();
}
// else we already have the correct answer

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...