Friday, September 18, 2009

Groovy how to read one line at a time

I am including this in my blog because I couldn't access the Groovy users forum last night. This is will be very helpful info for when one has to read one line (delimited by end of line character(s)) at a time. Eg., to stop after reading a certain number of lines, or to read from two files and compare data, which then determines which file to read from next.

Note that readLine does not work for File, and no longer works with FileInputStream

The first .readLine() reads a line
The next readLine returns an empty string "", but not null (until end of file).
Subsequent invocations of .readLine alternately return
a line, then an empty string.

At end of file, readLine starts returning null.
This also tests as an empty string ""

Reading past the end of file continues to return null
It does not cause an abend

I have included the pgm I used to determine how to use this, with comments that give my findings.

<target name="groovy.test.FileReader" description="">
<!-- .read() reads a single byte. Reading contineus form there .text() reads the remainder of the file ---->
lineCnt1 = 0
lineCnt2 = 0
f1 = new FileReader("C:/temp2.txt")

// if .read followed by .readline, it starts reading after the byte
// already read by the .read
aLine = //read first byte of line 1 as number value of the byte.
println "aLine = [" + aLine + "]" // "C" prints as 67

for (lineCnt1 in 1..15) { // note: lineCnt is local to the for loop


def readALineRtn(lineNbr) {
//aLine = f1.text // reads rest of file, including end of line characters
aLine = f1.readLine()
println lineNbr + " aLine = [" + aLine + "]"
switch (aLine) {
case null: println " NULL"
case "": println " empty string"


println "lineCnt1 = " + lineCnt1
println "lineCnt2 = ${lineCnt2}"



alex said...

Funny I ran into this issue, but there is a simple solution: use BufferedReader( FileReader)

// ------------------
BufferedReader fIn = new BufferedReader(new FileReader( "c:/tmp/blah.txt" ));

// do stuff... like get the headers out
def row = fIn.readLine()
// and print it out
println row

row = it.value
// process row...
println row

Patricia said...

thanks, Alex

Post a Comment