Monday, July 4, 2011

Standard Java/Groovy Directory Properties

I mostly use Groovy for scripting and many of my scripting needs require the ability to navigate directory structures. In writing such scripts, it is helpful to know which properties are available out of the box for the Groovy script developer. This short post summarizes some of the most common properties available to a Groovy script via Java standard Properties and Groovy's own property.

Java provides several useful properties for determining directories. These include user.dir (user directory AKA working directory or current directory), user.home (user's home directory), java.io.tmpdir (directory for temporary files), and java.home (base directory of applicable JRE installation, often corresponding to $JAVA_HOME or %JAVA_HOME% environment variables).

Groovy adds it own useful directory property with groovy.home, a property which points to the base directory of the applicable Groovy installation. In other words, groovy.home is to the Groovy installation what java.home is to the Java installation. The following simple Groovy script shows each of these properties in action.

demoJavaPlusGroovyDirectoryProperties.groovy
#!/usr/bin/env groovy
/**
 * demoJavaPlusGroovyDirectoryProperties.groovy
 */
println "User Directory (user.dir):\n\t${System.getProperty('user.dir')}"
println "Current Directory (.):\n\t${new File(".").canonicalPath}"
println "User Home (user.home):\n\t${System.getProperty('user.home')}"
println "Java Home (java.home):\n\t${System.getProperty('java.home')}"
println "Groovy Home (groovy.home):\n\t${System.getProperty('groovy.home')}"
println "Temporary Directory (java.io.tmpdir):\n\t${System.getProperty('java.io.tmpdir')}"

The next screen snapshot shows the above script being run twice from its own containing directory and from one directory higher than that. As the output from running the script twice shows, the current directory provided by "." matches that provided by the property user.dir in both cases.


Access to these properties within Groovy scripts can be useful in a variety of contexts. Scripts can use this information to know where files are placed for standard situations and to provide this information in script output to the user. Use of these properties can also reduce hard-coded directories within the script.

No comments: