Groovy file magic with AntBuilder

September 3rd, 2010 | Tags: ,

The more I work with groovy the more I like it. While my love for groovy is best left for another post, I did spend quite a bit of time figuring out how to copy files from one directory to another using groovy’s build in AntBuilder. I figured i’d post my list of AntBuilder tsks here.

First, the simplest of them (something you’ll find all over the web), deleting an entire directory:

new AntBuilder().delete(dir: "D:/tmp/test")

Then slightly more useful, copying contents of an entire directory to another directory:

new AntBuilder().copy(todir: "E:/2") {
    fileset(dir : "E:/1")
}

Notice how seamless the snippet looks. The part that I like the most is that it’s extremely expressive, any novice starting out with groovy can understand what it means (with a bit of reading up on closures).

Ofcourse ant’s copy task is a lot more powerful than just the above snippet. We can use patterns to specify what should be copied. For example, copy all java files from one directory to another:

new AntBuilder().copy(todir: "E:/2") {
    fileset(dir : "E:/1") {
        include(name:"**/*.java")
    }
}

Anoter usage is to copy all java files except for test cases:

new AntBuilder().copy(todir: "E:/2") {
    fileset(dir : "E:/1") {
        include(name:"**/*.java")
        exclude(name:"**/*Test.java")
    }
}

I have to admit, I have never used ant before so I do not know what else you can do with it but combined with groovy it looks like i’ll be using it quite bit.

Share

No related posts.

No comments yet.