4

I have a directory that contains a list of files. I wanted to get the latest file out of all the contents of the said directory. How will I do that?

I am using this code, but I am not getting the latest file out of it. Please help.

def fileDir = new File("A/B").listFiles().first()

Thanks.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
chemilleX3
  • 1,176
  • 5
  • 17
  • 27
  • there is a similar question on how to do that in java. you can use that in groovy too and propably simplify it a bit... http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified – moeTi Nov 08 '12 at 08:53

1 Answers1

13

As simple as:

new File( 'A/B' ).listFiles()?.sort { -it.lastModified() }?.head()

(taking the negative lastModified, as we want the newest file first)

tim_yates
  • 167,322
  • 27
  • 342
  • 338