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).
Solution 1:
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:
-
Your application is located at
C:\MyJar.jar
Open the shell (cmd.exe) and
cd
to C:\test\subdirectory.Start the application using the command
java -jar C:\MyJar.jar
.The first two calls return 'C:\test\subdirectory'; 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:\eclipse\workspaces\YourProject\bin\
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
Solution 2:
In .NET (C#, VB, …), you can query the current Assembly
instance for its Location
. However, this has the executable's file name appended. The following code sanitizes the path (using System.IO
and using System.Reflection
):
Directory.GetParent(Assembly.GetExecutingAssembly().Location)
Alternatively, you can use the information provided by AppDomain
to search for referenced assemblies:
System.AppDomain.CurrentDomain.BaseDirectory
VB allows another shortcut via the My
namespace:
My.Application.Info.DirectoryPath
Solution 3:
In Windows, use the WinAPI function GetModuleFileName(). Pass in NULL for the module handle to get the path for the current module.
Solution 4:
Python
path = os.path.dirname(__file__)
That gets the path of the current module.