Monday, February 21, 2011

Java's File.deleteOnExit() in Groovy

I've blogged before (File.deleteDir(), File.getText(), and More File Fun) on the useful features that Groovy's GDK extension of the File class adds to Java's File class. However, Java's File class is no slouch itself and brings some highly useful functionality to Groovy scripts (and obviously Java applications) without any Groovy extensions required. In this post, I look at one such method: Java's File.deleteOnExit().

Java's File.deleteOnExit() has been available since JDK 1.2. The documentation for this method states:
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.

This simple method is simply demonstrated in the next Groovy code listing.

#!/usr/bin/env groovy
 * Demonstrate using Java's File.deleteOnExit() method in a Groovy script.
def tmpFile = new File("temp.txt")
tmpFile << "Dustin was here!"
println "${tmpFile.text}"

The above example is silly, but demonstrates the functionality. In a more realistic situation, a temporary file might be created to be acted upon by other file-handling capabilities in Groovy or other products. If the file truly is temporary and is merely a means to an end, then it is nice to have it automatically removed upon JVM exit.

When the line above that invokes the deleteOnExit() method is not present or is commented out, the "temporarily" created file is left around when the script finishes. The next screen snapshot demonstrates this.

When the invocation of deleteOnExit() is executed, the "temporarily" completed file is removed automatically upon successful completion of the script. This is demonstrated in the next screen snapshot.

Because deleteOnExit() is a method on the Java version of the File class, it is obviously available to Java applications as well as Groovy scripts. However, it is my experience that I use this type of functionality more often within scripting than in regular application development. It is obviously possible to clean up after oneself with explicit file deletion calls, but I like the automatic handling of removing upon exit provided by Java's File.deleteOnExit() method for clearer and more concise scripts. Because many of my scripts are self-contained and relatively small, and because Groovy kicks off a new JVM for each individual execution of my Groovy script, I know that the file deletion takes place in a timely manner.

No comments: