Thursday, June 25, 2009

Groovy: Find files modified in the last X days

On a recent project there was a requirement to search a directory (and all sub-directories) for any files (all files were images) changed in the last 7 days and load them into a database table. The code was being written in Groovy and being lazy I just used the *nix find command and processed the command output. I wanted to avoid writing the code to recurse the directories thinking it would be easier to write, read and maintain if I just processed the find command output.

I took a look today and found out how easy Groovy makes this, so when I have a chance I'll rewrite using the code below to make it pure Groovy and portable between *nix and Windows.


File rootDir = new File("d:/temp") // arg[0] == d:/temp
long checkTime = new Date().minus(7).time // arg[1] == 7
rootDir.eachFileRecurse {
if (it.isFile() && it.lastModified() >= checkTime) {
println "${it} [${new Date(it.lastModified())}]"
// call the method to load this image file...
}
}

Tuesday, June 9, 2009

Using Groovy to pad a file

The other day someone asked me if there was a quick way to right-pad lines in a file with spaces to a certain length. I couldn't find a setting to do this in my favorite text editor Notepad++, so I thought I'd see what it would take to do in Groovy.

Not a very exciting script, but I truly admire how much you can do with Groovy in just a few lines of code.


def outfile = new File("out.txt")
def infile = new File("in.txt")

outfile.withWriter { output ->
infile.eachLine { input ->
output.writeLine(input.padRight(200, " "))
}
}