Alex Rivera | Logout

How to neatly print new line in Groovy?

Asked 2010-09-15T13:45:56.460
15

I was wondering if there is any neat way to write new line into the file from Groovy. I have the following script:

new File("out.txt").withWriter{ writer ->
    for(line in 0..100) {
            writer << "$line"
    }
}

I could use writer << "$line\n" or writer.println("$line"), but I was wondring if there is any way to use << operator to append the new line for me.

Edit
Report

1 Answer

6

You could use meta programming to create that functionality. An easy solution to change the behaviour of the << operator would be to use a custom category.

Example:

class LeftShiftNewlineCategory {
    static Writer leftShift(Writer self, Object value) {
        self.append value + "\n"
    } 
}
use(LeftShiftNewlineCategory) {
    new File('test.txt').withWriter { out ->
        out << "test"
        out << "test2"    
    }
}

More about categories here: http://docs.codehaus.org/display/GROOVY/Groovy+Categories

answered 2010-09-15T14:28:41.810

Your Answer