How to neatly print new line in Groovy?

Or you could just use three double-quotes

e.g.

def multilineString = """
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
"""
println multilineString

Reference: http://grails.asia/groovy-multiline-string


It's a nice idea to ask the system for the correct line separator as these can change between operating systems.

writer << "Line 1" + System.getProperty("line.separator") + "Line 2"

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

Tags:

Groovy