1

When I launch my Java application from the command line, I would like to know the place in the file system the console was at before I call my script. I basically want to know my pwd from inside the Java application, is this possible? I do not see anything in System.getProperty(""). The user.dir property does not work, it just gives me the location of where my .project file is for my Eclipse project.

I am able to get the right path within my python script with os.getcwd(), but I cannot figure out yet how to get that path into my Java program.

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
smuggledPancakes
  • 9,881
  • 20
  • 74
  • 113
  • 1
    This is better known as the current working directory, not the path. Path typically refers to the environment variable called PATH which is the list of directories that are searched for executables or libraries. You could say 'the path of the cwd' but that's redundant. – Sarel Botha Apr 19 '12 at 20:14

4 Answers4

3

Try this:

  File f = new File(".");
    f.getCanonicalPath(); // returns the path you are looking for

You can also use :

System.getProperty("user.dir")

There are some good answers on the following question that might be helpful: Get the application's path

Community
  • 1
  • 1
Colin D
  • 5,641
  • 1
  • 23
  • 35
  • Couldn't that create an issue, if the user who is running it doesn't have read/write access in the PWD? I know the "." will exist, but in some special contexts I think that could be an issue? – kevingreen Apr 19 '12 at 19:51
  • no, creating a 'File' object does not open or create the file. – Colin D Apr 19 '12 at 19:53
1

Try this:

CodeSource cs = getClass().getProtectionDomain().getCodeSource();

Then cs.getLocation();

That will be your PWD on execution.

ED: CodeSource is part of this library: import java.security.CodeSource;

kevingreen
  • 1,541
  • 2
  • 18
  • 40
1

I usually use this:

System.out.println(getClass().getClassLoader().getResource(".")
                .getPath());

which returns the same result as @kevingreen suggests

Kennet
  • 5,736
  • 2
  • 25
  • 24
  • I suppose yours is cleaner then, it doesn't involve another Import. – kevingreen Apr 19 '12 at 20:24
  • Well, @kevingreen System.out.println(getClass().getProtectionDomain().getCodeSource() .getLocation().getPath()); doesn't involve any import either;-) I learned something new from you, thanks! – Kennet Apr 20 '12 at 10:06
-2

Try this:

System.getProperty("user.home")
evanwong
  • 5,054
  • 3
  • 31
  • 44
  • That will only get the home directory of the user account that is running the application. Not the PWD the app is running under. – kevingreen Apr 19 '12 at 19:45