Mike Sallese Mike Sallese - 1 year ago 124
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download