Search

Dark theme | Light theme

November 9, 2009

Groovy Goodness: withReader and withWriter

Normally when we are working with readers and writers in Java we must make sure we close the appropriate reader and writer. Groovy has several with...() methods for File, URL or streams and writers, where ... is the name of the reader or writer. We pass a closure to these methods and Groovy makes sure all readers and writers are closed correctly, even if exceptions are thrown in the closure.

def file = new File('sample.txt')

file.withWriter('UTF-8') {
    it.writeLine 'Adding this text to the file.'
}

def s 
file.withReader('UTF-8') {
    s = it.readLine()
}

assert 'Adding this text to the file.' == s