Dark theme | Light theme

May 31, 2011

Groovy Goodness: Transforming Reader Input to Writer Output

With Groovy we can immediately transform the input from a Reader object(like a file, URL or other input type) to a Writer object (like a file, URL or other output type). Groovy adds the transformLine(Writer, Closure) and transformChar(Writer, Closure) methods to the Reader class. We need to pass the Writer object that will contain the transformed output as the first argument. The second argument is a closure with the rules for the transformation that needs to be applied.

def reader = new StringReader('''\
Groovy's support
for transforming reader input to writer output.

def writer = new StringWriter()

reader.transformLine(writer) { line ->  
    if (line.matches(~/^Groovy.*/)) {
        line = '>>' + line.replaceAll('Groovy', 'GROOVY') + '<< '

def resultTransformLine = writer.toString()

reader = new StringReader(resultTransformLine)
writer = new StringWriter()
reader.transformChar(writer) { ch ->
    ch in ['\n', '\r'] ? '' : ch

assert writer.toString() == ">>GROOVY's support<< for transforming reader input to writer output."