Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Saturday, February 19, 2011

A Groovy Script That Uses Dates and Files

Groovy is a flexible scripting languages that's backed by the standard libraries of Java.  A script written in Groovy can use standard Java operators like "+" and libraries like java.util.Date with a slight syntactic difference.

If you work in Java for a while, you'll find the compiliation step introduces a slight lag.  Command-line jobs need to be compiled before being run.  Classloaders need to be refreshed when working on a webapp.  Groovy skips the compilation step, so you spend less time with Maven or Ant scripts.

Groovy has access to all of the Java libraries available to Java SE (and EE).  So, you can use your knowledge of the JDK and Java operators like "+" rather than learn a new syntax.

There is a syntactic difference in Groovy, but if you've working in JavaScript, Python, or another loosely-typed language, it shouldn't be too hard to overcome.  You don't need to be as formal with declarations, there are some implicit objects, and special closures reduce the amount of code you need to write.

The following Groovy script outputs the contents of a directory with a header row that contains a timestamp.  The scripts writes the contents out to a file.  The file's name is timestamped.  This script is in a file called 'ls.groovy'; '.groovy' is the standard suffix for Groovy scripts.


1 def fn = "dir.txt"
2 def today = new Date()
3 def c = new GregorianCalendar()
4 def sdf = new java.text.SimpleDateFormat("yyyyMMddhhmmss")
5
6 // add a timestamp to the file
7 fn = fn.replace(".", "-" + sdf.format(today) + ".")
8
9 println "Creating file contents report '" + fn + "'"
10
11 new File(fn).withWriter { out ->
12 out.writeLine("File contents " + today + ":")
13 out.writeLine("-------------------------------------------------")
14 new File(".").listFiles().each { f ->
15 out.writeLine(f.name)
16 }
17 }


Lines 1-4 define some variables. Line 1 uses a literal string. Lines 2 and 3 ('today' and 'c') creates Java objects. Notice that there are no imports needed for this. Both Date and GregorianCalendar belong to the java.util package. Line 4 also creates a Java object, but I had to add the package name.

Line 7 maniupulates the filename string, adding a timestamp to the filename.

Line 9 prints out some logging information. Notice that the function is available and doesn't need an object reference like System.out.println.

Line 11 creates a File object that will hold the output of the script. 'out' is a variable that binds to the result of the next four lines.

Lines 12-13 write out text strings. Line 12 uses the 'today' variable.

Line 14 is another closure that bind the File variable f to the out.writeLine(f.name) statement.

While this script is easy to code with standard Java, the resulting Java class would contain much more code. For example, there would be a class, a 'public static void main', shorthand for loops, etc. Moreover, you couldn't simply run the Java program without an Ant or Maven build file (or command). This script runs quickly with a single 'groovy ls.groovy'. It's worth considering Groovy if you're starting a new Java project.

No comments:

Post a Comment