tags:

views:

36

answers:

2

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.

A: 

Have you tried

writer << "$line" << "\n"

Which is shorthand for

writer << "$line"
writer << "\n"
Riduidel
+2  A: 

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

xlson
This is nice stuff. I've just started with Groovy few days ago and wasn't aware of that feature. I must check it out! Thanks xlson.
pregzt
You're welcome! :) There's many different ways to use meta-programming in Groovy to enhance existing APIs. The good thing with categories (imho) is that they are scoped so that you don't change behavior in all of your program. Check out this intro to Groovy meta-programming if you wanna learn more about it: http://www.ibm.com/developerworks/java/library/j-pg06239.html
xlson