Mike Sallese Mike Sallese - 2 months ago 13
Groovy Question

Get the last line of a file in groovy

Google doesn't give any great results for getting the last line of a file in groovy so I feel this question is necessary.

How does one get the last line of a file in groovy?

Answer

Get all lines, then get the last one:

def lines=new File("/home/user/somefile.txt").readLines()
def lastline=lines.get(lines.size()-1)

Or, if the file is dangerously large:

def last=new File('/home/user/somefile.txt').withReader {  r-> r.eachLine {it} }

which is almost identical to asker's answer.