January 2, 2010

Groovy Goodness: Normalize and Denormalize Linefeeds and Carriage Returns

Each platform where we can run Java and Groovy applications has different line separators. Groovy adds two methods to the String class to convert the specific platform line separator to linefeeds and vica versa.

def text = 'First line\r\nSecond line\r\n'
def textNormalized = text.normalize()
def platformLineSeparator = System.properties['line.separator']

assert 'First line\nSecond line\n' == textNormalized
assert "First line${platformLineSeparator}Second line${platformLineSeparator}" == textNormalized.denormalize()