35

I've got a little script I'm using a paramter to pass in the current execution directory, but would like to make it a little more robust.

How does one find out the base execution directory?

Scott Bennett-McLeish
  • 9,017
  • 11
  • 39
  • 47

3 Answers3

44

Try this:

System.getProperty("user.dir");
rodion
  • 14,389
  • 3
  • 51
  • 55
23

Depending on the security model, if the System.getProperty(String) is not allowed, you can use

String currentDir = new File(".").getAbsolutePath()
Aleks G
  • 54,795
  • 26
  • 160
  • 252
  • 2
    That workaround won't help. The javadoc for `getAbsolutePath()` says throws *"`SecurityException` - If a required system property value cannot be accessed."* – Stephen C Jun 27 '11 at 11:59
  • 7
    It should be new File(".").getAbsoluteFile().getParent() - this removes the trailing "/." from the path. – CodeMonkeyKing Apr 27 '15 at 20:47
20

For reference:

The accepted answer on the question here is what I was looking for.

As an example, when calling c:\scripts\MyScript.groovy from c:\users\Scott\ I wanted to know c:\scripts\.

This is done via this:

def scriptDir = getClass().protectionDomain.codeSource.location.path

Where scriptDir is assigned something like:

/c:/scripts/MyScript.groovy

Community
  • 1
  • 1
Scott Bennett-McLeish
  • 9,017
  • 11
  • 39
  • 47
  • 6
    Yes, your question isn't worded well. You needed to ask "how to get the location of the class". Glad you found the answer though. – Aleks G Jun 27 '11 at 13:53