Saturday, April 14, 2012

Deleting All .class Files with Groovy

When running simple Java tests either to learn how something works in Java or to build examples for my blog posts, I often store the examples in the same directory on my machine. I decided that I wanted to remove all the generated .class files from this directory. There are several approaches to doing this on a Linux machine, but I wanted to remove these files on a Windows machine. I know there are tools and ways to do this on Windows, but I knew it would take me less time to write a simple Groovy script to do it than to search online for such a tool. This post provides and briefly describes the simple Groovy script for removing .class files.

deleteClassFiles.groovy
#!/usr/bin/env groovy
if (args.length < 1)
{
   println "Please specify directory under which .class files should be removed"
   println "  (including .class files in sub-directories)."
   System.exit(-1)
}

def directoryName = args[0]
println "Remove .class files in ${directoryName} and its subdirectories..."
def directory = new File(directoryName)
def classPattern = ~/.*\.class/
directory.eachFileRecurse(groovy.io.FileType.FILES)
{ file ->
   if (file ==~ classPattern)
   {
      println "Deleting ${file}..."
      file.delete()
   }
}

The above script will remove all files that have names ending with a .class suffix in the provided directory or any of its sub-directories. The directory is specified via a single command-line argument to the script, so I did not use Groovy's built-in CLI support in this case. The script instead relies on Groovy's implicit availability of the args parameter representing the command line arguments.

The Groovy script featured in this post takes advantage of the Groovy GDK File extension's eachFileRecurse method to recursively iterate through the names of the files in the provided directory and its subdirectories. Another convenient Groovy feature employed in this script is application of Groovy regular expression support to specify the pattern (file names ending with ".class" extension) and then to use the pattern matcher in the conditional that decides which files are to be deleted.

The above script prints out the files to be deleted as it deletes them. One could easily enhance the script to accept a parameter that would display files that would be deleted without actually deleting them. For me, this script was more proof that Groovy is so easy to use that sometimes it's easier to write a new script in Groovy to accomplish daily tasks than it is to find existing tools and scripts online to download.

2 comments:

tcherno said...

Hi, you can use traverse to filter files with pattern :


directory.traverse(type: groovy.io.FileType.FILES, nameFilter: classPattern) {

Dustin said...

tcherno,

Thanks for pointing out that nice alternative.

Dustin