Sep 4 2010

Processing Files In Place With Groovy

I recently had the need to process a bunch of files and directory structures that were emitted from a generation process that I didn’t have control over.  The basic needs were to delete some files, delete some directories, and to modify selected content of some of the files.  This is a very straight forward, trivial thing to do but I was looking for a solution that was both cross platform and very quick to develop. I also had to deal with a bit of XML and wanted an easy way to parse and modify XML documents in a natural way.   This post shows how to do this using a Groovy script.  I’ve been using Groovy for testing of Java code and other one off random tasks for a couple years now but it still surprises me how fast you can accomplish certain tasks yet keep your code readable and at a relatively high level of abstraction, especially compared to shell scripts, sed, awk.

In a nutshell, the following method will process a file in place.

def processFileInplace(file, Closure processText) {
    def text = file.text

If you know Groovy, this probably doesn’t require any additional explanation. But if you don’t know Groovy, don’t worry. The remainder of this post shows examples of using this method and touches on a few details regarding file and directory deletion.
Continue reading