views:

9445

answers:

14

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

+1  A: 

In Java, there are two ways to find the application's path. One is to employ System.getProperty:

System.getProperty("user.dir");

Another possibility is the use of java.io.File:

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

Yet another possibilty uses reflection:

getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
Konrad Rudolph
Note that this is a bit misleading/confusing. The three methods you quote can give completely different results!
Zarkonnen
Zarkonnen: You're right but as implied in my original posting, I'm no expert. This is a community wiki. Please feel free to edit/correct my answer!
Konrad Rudolph
+12  A: 

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
Konrad Rudolph
Upvoted for :System.AppDomain.CurrentDomain.BaseDirectory
p.campbell
A: 

In bash, the 'pwd' command returns the current working directory.

Ced
Unfortunately, `pwd` returns the current working directory which may differ from the path of the script.
Konrad Rudolph
The answer is actually found in http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-in
Konrad Rudolph
+2  A: 

Delphi

In Windows applications:

Unit Forms;
path := ExtractFilePath(Application.ExeName);

In console applications:

Independent of language, the first command line parameter is the fully qualified executable name:

Unit System;
path := ExtractFilePath(ParamStr(0));
Ralph Rickenbach
+6  A: 

Python

path = os.path.dirname(__file__)

That gets the path of the current module.

Fara
+1  A: 

in Ruby, the following snippet returns the path of the current source file:

path = File.dirname(__FILE__)
bltxd
+1  A: 

Unix

In unix one can find the path to the executable that was started using the environment variables. It is not necessarily an absolute path, so you would need to combine the current working directory (in the shell: pwd) and/or PATH variable with the value of the 0'th element of the environment.

The value is limited in unix though, as the executable can for example be called through a symbolic link, and only the initial link is used for the environment variable. In general applications on unix are not very robust if they use this for any interesting thing (such as loading resources). On unix, it is common to use hard-coded locations for things, for example a configuration file in /etc where the resource locations are specified.

Paul de Vrieze
+5  A: 

In Windows, use the WinAPI function GetModuleFileName(). Pass in NULL for the module handle to get the path for the current module.

MrZebra
+1  A: 

Libc
In *nix type environment (also Cygwin in Windows):

  #include <unistd.h>

   char *getcwd(char *buf, size_t size);

   char *getwd(char *buf); //deprecated

   char *get_current_dir_name(void);

See man page

Rajish
+1  A: 

In CFML there are two functions for accessing the path of a script:

getBaseTemplatePath()
getCurrentTemplatePath()

Calling getBaseTemplatePath returns the path of the 'base' script - i.e. the one that was requested by the web server.
Calling getCurrentTemplatePath returns the path of the current script - i.e. the one that is currently executing.

Both paths are absolute and contain the full directory+filename of the script.

To determine just the directory, use the function getDirectoryFromPath( ... ) on the results.

So, to determine the directory location of an application, you could do:

<cfset Application.Paths.Root = getDirectoryFromPath( getCurrentTemplatePath() ) />

Inside of the onApplicationStart event for your Application.cfc



To determine the path where the app server running your CFML engine is at, you can access shell commands with cfexecute, so (bearing in mind above discussions on pwd/etc) you can do:

Unix:

<cfexecute name="pwd"/>

for Windows, create a pwd.bat containing text @cd, then:

<cfexecute name="C:\docume~1\myuser\pwd.bat"/>

(Use the variable attribute of cfexecute to store the value instead of outputting to screen.)

Peter Boughton
+8  A: 

In Java the calls to

System.getProperty("user.dir")

and

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

return the current working directory.

The call to

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

may return the path to the executable.

Example:

  1. Your application is located at

    C:\MyApp.exe

  2. Open the shell (cmd.exe) and switch to C:\test\subdirectory

  3. Start the application using the command 'C:\MyApp.exe'

  4. The first two calls return 'C:\test\subdirectory' the third call returns 'C:\MyApp.exe'

Be aware the results for getClass()... can be different depending on how you start the application.

When debugging, 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 directories for the generated class files.

For an executable, for instance created using Launch4J, the result will be the full path and the name of the executable, e.g. 'C:\dir...\YourApplication.exe'.

A complete example to get the application directory without executable name or the corresponding path to the class files when debugging:

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

if (applicationDir.endsWith(".exe"))
{
    applicationDir = new File(applicationDir).getParent();
}
else
{
    // Add the path to the class files  
    applicationDir += getClass().getName().replace('.', '/');

    // Step one level up as we are only interested in the 
    // directory containing the class files
    applicationDir = new File(applicationDir).getParent();
}
+1  A: 

Objective-C Cocoa (Mac OS X, I don't know for iPhone specificities):

NSString * applicationPath = [[NSBundle mainBundle] bundlePath];
mouviciel
+1  A: 

Tcl:

Path of current script:

set path [info script]

Tcl shell path:

set path [info nameofexecutable]

If you need the directory of any of these, do:

set dir [file dirname $path]

Get current directory:

set dir [pwd]
Cristi Diaconescu
+2  A: 

In .Net you can use

System.IO.Directory.GetCurrentDirectory

to get the current working directory of the application, and

My.Application.Info.DirectoryPath

to get the directory of the exe.

d7samurai