tags:

views:

41

answers:

1

I have a directory named 'import' and would like to get all files and their corresponding date (based on filename). Sample content of the directory is this:

  • input_02202010.xls
  • input_02212010.xls
  • input_02222010.xls

I would like to have a Map that contains the path of the file and a Date variable.

Can anyone show me how Groovy will solve this?

+2  A: 

Use new File("/foo/bar/import").list() to get the file names, just like you would in Java. Then create file objects from the strings and check lastModified() for the last modification date.

EDIT: Groovy adds eachFile() methods to java.io.File, we can use that to make it a bit more groovy...

To extract the date from the filename, use

Date d = new java.text.SimpleDateFormat("MMddyyyy").parse(filename.substring(6,14))

To make it all into a map (using the filename as key and the date as value, though redundant):

def df = new java.text.SimpleDateFormat("MMddyyyy")
def results = [:]
new File("/foo/bar/import").eachFile() { file -> 
   results.put(file.getName(), df.parse(file.getName().substring(6,14)))
}

results
ammoQ
thanks for the reply. would like to know how to extract the date string from the filename using Groovy - Regex: http://groovy.codehaus.org/Regular+Expressionsi.e. input_02202010.xls -> 02202010
firnnauriel
def s = "input_02222010.xls"def s2 = s =~ /input_([\d]+)\.xls/assert "02222010" == s2[0][1]
John Wagenleitner