Get the path to the application

I recently searched for how to get the Java application directory. I finally found the answer, but I needed a surprisingly long time, because the search for such a generic term is not easy. I think it would be nice to make a list of ways to achieve this in several languages.

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

Clarification:

There is a great difference between the directory that contains the executable and the current working directory (given by pwd under Unix). Initially, I was interested in the former, but do not hesitate to publish methods for determining the latter (specifying what you mean).

+80
language-agnostic path
Oct. 20 '08 at 11:07
source share
21 answers

In Java calls

 System.getProperty("user.dir") 

and

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

returns the current working directory.

Call

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

returns the path to the JAR file containing the current class, or the CLASSPATH element (path) that the current class gave if you use it directly from the file system.

Example:

  • Your application is in

      C:\MyJar.jar 
  • Open a shell (cmd.exe) and cd in the subdirectory C: \ test \.

  • Launch the application using the java -jar C:\MyJar.jar .

  • The first two calls return 'C: \ test \ subdirectory'; the third call returns "C: \ MyJar.jar".

When launched from the file system, and not the JAR file, the result will be the path to the root of the files of the generated classes, for example

 c:\eclipse\workspaces\YourProject\bin\ 

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

Full example to get the application directory without the name .jar or the corresponding path to the class files, if it is executed directly from the file system (for example, during debugging):

 String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (applicationDir.endsWith(".jar")) { applicationDir = new File(applicationDir).getParent(); } // else we already have the correct answer 
+58
Mar 24 '09 at 7:17
source share

In .NET (C #, VB, ...) you can query the current Assembly instance for its Location . However, this adds the name of the executable file. 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 reference assemblies:

 System.AppDomain.CurrentDomain.BaseDirectory 

VB allows you to use another shortcut through the My namespace:

 My.Application.Info.DirectoryPath 
+22
Oct. 20 '08 at 11:07
source share

On Windows, use the WinAPI GetModuleFileName () function. Go to NULL for the module descriptor to get the path for the current module.

+9
Oct 20 '08 at 12:24
source share

Python

 path = os.path.dirname(__file__) 

This gets the path to the current module.

+7
Oct 20 '08 at 11:27
source share

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

 NSString * applicationPath = [[NSBundle mainBundle] bundlePath]; 
+5
Mar 24 '09 at 15:43
source share

In Java, there are two ways to find the path to a program. One of them is to use System.getProperty :

 System.getProperty("user.dir"); 

Another possibility is to use java.io.File :

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

Another possibility uses reflection:

 getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 
+4
Oct. 20 '08 at 11:07
source share

In .Net you can use

System.IO.Directory.GetCurrentDirectory

to get the current working directory of the application, and in VB.NET you can use

My.Application.Info.DirectoryPath

to get the exe directory.

+4
Oct 28 '10 at 17:38
source share

In VB6, you can get the path to the application using the App.Path property.

Note that this will not have a trailing \ EXCEPT when the application is in the root directory of the drive.

In the IDE:

 ?App.Path C:\Program Files\Microsoft Visual Studio\VB98 
+4
Jul 31 2018-12-12T00:
source share

Delphi

In Windows applications:

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

In console applications:

Regardless of the language, the first command line parameter is the full executable name:

 Unit System; path := ExtractFilePath(ParamStr(0)); 
+3
Oct. 20 '08 at 11:23
source share

Libc
In an environment like * nix (also Cygwin on 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

+3
Oct 20 '08 at 12:25
source share

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

+2
Oct. 20 '08 at 11:15
source share

Unix

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

The value is limited in unix, although since the executable can, for example, be called via a symbolic link, and only the start link is used for the environment variable. In general, unix applications are not very reliable if they use it for any interesting thing (for example, loading resources). Unix typically uses hard-coded locations for things, such as a configuration file in /etc , where resource locations are specified.

+2
Oct. 20 '08 at 12:15
source share

In tcl

Current script path:

 set path [info script] 

Tcl shell path:

 set path [info nameofexecutable] 

If you need a directory of any of them, follow these steps:

 set dir [file dirname $path] 

Get the current (working) directory:

 set dir [pwd] 
+2
Aug 11 '10 at 16:09
source share

In PHP :

 <?php echo __DIR__; //same as dirname(__FILE__). will return the directory of the running script echo $_SERVER["DOCUMENT_ROOT"]; // will return the document root directory under which the current script is executing, as defined in the server configuration file. echo getcwd(); //will return the current working directory (it may differ from the current script location). ?> 
+2
Dec 14 '11 at 4:30
source share

in Android

 getApplicationInfo().dataDir; 

to get the sd card i use

 Environment.getExternalStorageDirectory(); Environment.getExternalStoragePublicDirectory(String type); 

where the latter is used to store a file of a certain type (audio / video, etc.). You have constants for these lines in your environment class.

Basically, for something with the application, use the ApplicationInfo class and for anything related to data in the SD card / External Directory using the environment class.

Docs: ApplicationInfo , Environment

+2
Feb 20 2018-12-12T00:
source share

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

 path = File.dirname(__FILE__) 
+1
Oct 20 '08 at 11:37
source share

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

 getBaseTemplatePath() getCurrentTemplatePath() 

The getBaseTemplatePath call returns the path of the "base" script - that is, the one requested by the web server.
The getCurrentTemplatePath call returns the path to the current script — that is, the currently executing one.

Both paths are absolute and contain the full directory + script file name.

To determine only the directory, use the getDirectoryFromPath( ... ) function for the results.

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

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

Inside the onApplicationStart event for your Application.cfc





To determine the path that the application server is running on which your CFML module is running, you can access shell commands using cfexecute, therefore (referring to the above discussion on pwd / etc), you can do:

Unix:

 <cfexecute name="pwd"/> 

For Windows, create pwd.bat containing the text @cd , and then:

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

(Use the variable cfexecute attribute to save the value instead of displaying it.)

+1
Dec 14 '08 at 22:33
source share

In cmd (Microsoft command line shell)

You can get the script name with% * (maybe relative to pwd)

This gets the script directory:

 set oldpwd=%cd% cd %0\.. set app_dir=%pwd% cd %oldpwd% 

If you find any mistakes you will make. Then correct or comment.

+1
Jul 03 '12 at 9:40
source share

I released https://github.com/gpakosz/whereami , which solves the problem in C and gives you:

  • path to the current executable file
  • path to the current module (different from the path to the executable when called from the shared library).

It uses GetModuleFileNameW on Windows, parses /proc/self/maps on Linux and Android, and uses _NSGetExecutablePath or dladdr on Mac and iOS.

+1
Jan 28 '15 at 16:54
source share

Java:

On all systems (Windows, Linux, Mac OS X), only the following works for me:

 public static File getApplicationDir() { URL url = ClassLoader.getSystemClassLoader().getResource("."); File applicationDir = null; try { applicationDir = new File(url.toURI()); } catch(URISyntaxException e) { applicationDir = new File(url.getPath()); } return applicationDir; } 
+1
Sep 06 '16 at 11:41
source share

Note for the answer "20 above, concerning only Mac OSX: if the executable JAR is converted to an" application "via the OSX JAR BUNDLER, then getClass (). GetProtectionDomain (). GetCodeSource (). GetLocation (); DO NOT return the current application directory, but Adds the internal directory structure of the application to the response This internal structure of the application: / theCurrentFolderWhereTheAppReside / Contents / Resources / Java / yourfile

Perhaps this is a small bug in Java. In any case, to get the right answer you need to use one or two methods, and both will deliver the correct answer, even if the application is running, for example. through a shortcut located in another folder or on the desktop.

Charles

SoundPimp.com

0
Jan 31 '12 at 12:25
source share



All Articles