Search code examples
groovy

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?


Solution

  • 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.