A Groovy Script
Groovy is an agile scripting language with a syntax that is Java-like but far less formal than Java's own making it concise, more powerfully expressive, hence groovy. What's more, Groovy integrates with existing Java libraries and compiles straight to Java bytecode making it indinstinguishable and interchangeable with any Java code.
Groovy is ideal for one off jobs such as simple scripts to drive existing API's, it's a glue language. Its built-in support for regular expressions, native support for common data types, and additional convenience methods for the JDK make it more expressive than regular Java and loosen up the rules a bit - no need to declare a variable's type for example.
Recently I got back several several CD's with digital images from a photo lab. The program that came with the CD's offered to copy the pictures to a hard-drive in separate folders and so I agreed. Later on I realized if I wanted to copy the images to a new location their names would collide since since each folder used the same naming convention. To remedy this I needed to rename all files adding the folder name to each file's name. However, I wanted to avoid doing that repetitively by hand.
Here is the Groovy script required to perform a rename on all files in a given directory.
dirName = "C:/MyPictures/Pic0001"
new File(dirName).eachFile() { file ->
def newName = (file.getName() =~ /.jpg/).replaceFirst("0001.jpg")
File f = new File(dirName + "/" + newName)
file.renameTo(f)
println file.getName() + " -> " + f.getName()
}
The script relies on the familiar java.io.File class as well as on regular expressions. Notice eachFile(), which is a Groovy extension. The absence of semicolons is intentional (i.e. legal) and so is the lack of paranthesis around the parameters to method calls such as println.
The code, which follows eachFile() is called a closure - it's a block of code, similar to a method but not required to live in a class (since Groovy compiles to Java code behind the scenes a closure is in fact compiled to a Java class with a single method). Closures can be assigned to variables and passed around as method parameters.
There is a lot more to Groovy than just the Groovy kit. There is GSQL (accessing databases), Grails (groovy on rails), GSP (Groovy server pages), GroovySOAP (accessing groovy web services), GroovySWT (wrapper around Eclipse graphical library), COM scripting, and much more to check out.