0

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?

Mike Sallese
  • 827
  • 1
  • 10
  • 24

4 Answers4

1

Here's what I ended up with:

    new File("/home/user/somefile.txt").eachLine {
        lastLine = it
    }

.eachLine iterates through each line of the text file and lastLine is set to the current iteration until eachLine finishes going through the file. Pretty straightforward.

Community
  • 1
  • 1
Mike Sallese
  • 827
  • 1
  • 10
  • 24
1

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.

Alexiy
  • 1,966
  • 16
  • 18
0

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

It depends on what you know about the file. If the lines in the file are fixed length then you could look at the file size, divide it by the length of each line and then use random file access to jump to the last line in the file and read it. That would be more efficient than reading the entire file. If you don't know the length of the lines then you are probably going to have to read the entire file and discard everything before the last line you read.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
0
def fruitString = '"banana","apple","orange"'

def fruitArray = fruitString .split(',').collect{it as String}

log.info(fruitArray[0]) //banana

println(fruitArray[1]) //apple
toyota Supra
  • 3,181
  • 4
  • 15
  • 19
J S
  • 1
  • 1