Thursday, August 14, 2008

Groovy File IO : Staying at the Ritz


Every few months, I find myself writing a quick utility where, among other things, I want to copy a file. Usually within an hour, I want not only to copy the file but do a simple substitution as well.

I don't have a particular example here, but note that this usually involves some other computation: it isn't something as simple as a Bash script.

I've come to realize that the file IO aspect is often a good benchmark for the 'friendliness' of a language.


Imagine that this exercise is like needing a place to stay for the night. I just need some 'computational shelter' to get my stuff done. I'm not looking for anything profound or scalable.

Whenever I'm in Java, and I need to write this utility, I feel like I'm about to buy a house. There is a lot of paperwork involved and the process is not particularly fun. Plus, there is a conceptual mismatch: if I wanted to buy a house, that would be one thing, but I just want to stay overnight.

By contrast, when working with Groovy, I feel like I'm staying at the Ritz (a phrase I use often in person). I feel as though there are people attending to my needs, and they are friendly. Start the bath running, pour some wine, and relax....


Check out the examples below. The first is a straight copy. This is not an ultra-efficient use of Groovy/Java libraries but it does lead nicely to the second version with a substitution. Note that this is a glorious use of closures as the withWriter method will flush and close the file.

// straight copy (not optimally efficient)

new File('new.txt').withWriter { file ->
new File('orig.txt').eachLine { line ->
Even if you don't know Groovy, you can probably grok this code, which are complete programs. Note that x -> declares a parameter (named x) for a closure.

And with the substitution:

// copy with substitution

new File('new.txt').withWriter { file ->
new File('orig.txt').eachLine { line ->
file.writeLine( line.replace('code', 'joy') )

Check out the Groovy JDK and enjoy a luxurious evening tonight!


Michael Easter said...

Readers can download some IO examples over at Easter's Eggs for Groovy on GitHub

site said...

Quite worthwhile material, thank you for the post.

life_is_beautiful said...

Lovely code snippet !! This should have also been posted on stack overflow.

Copying one file to another has never been so simple :
new File("new.txt").withWriter { bufferedWriter ->

new File("orig.txt").eachLine { line ->