Library contents

Groovy String.readLines

Groovy's readLines on text returns a list of lines with their terminators removed. Blank lines inside the text remain in the list.

A simple example

String.readLines

  1. Start with Two lines, A then B
  2. Do this Read one line at a time
  3. Result Two records
The line reader allows the first line to be processed before the second.

Syntax

Groovy syntax
text.readLines()
Run this example in Groovy

Save the program as Lesson.groovy. Use Groovy 4 on the JVM.

groovy Lesson.groovy

Keep a blank record while splitting text into lines

An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.

First output line[A]
Lesson.groovy
def records = "A\r\n\nB".readLines()
records.each { line -> println '[' + line + ']' }
Output
[A]
[]
[B]

An unterminated final line is still present. This convenience method materializes the entire list, so use a reader for a large streaming source.

Groovy documentation for String.readLines

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1