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?
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?
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.
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.
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.
def fruitString = '"banana","apple","orange"'
def fruitArray = fruitString .split(',').collect{it as String}
log.info(fruitArray[0]) //banana
println(fruitArray[1]) //apple