39

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,187
  • 11
  • 41
  • 47

3 Answers3

48

Try this:

System.getProperty("user.dir");
rodion
  • 14,729
  • 3
  • 53
  • 55
28

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

String currentDir = new File(".").getAbsolutePath()
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • 4
    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
  • 8
    It should be new File(".").getAbsoluteFile().getParent() - this removes the trailing "/." from the path. – CodeMonkeyKing Apr 27 '15 at 20:47
21

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,187
  • 11
  • 41
  • 47
  • 7
    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