2010-02-24 64 views
1

我有一個名爲'import'的目錄,並希望獲得所有文件及其相應的日期(基於文件名)。該目錄的示例內容是這樣的:獲取文件列表

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

我想有一個包含文件的路徑和地圖Date變量。

任何人都可以告訴我Groovy如何解決這個問題嗎?

回答

3

使用new File("/foo/bar/import").list()來獲取文件名,就像在Java中一樣。然後從字符串創建文件對象,並檢查lastModified()是否爲最後修改日期。

編輯: Groovy的增加eachFile()方法java.io.File的,我們可以用它來使它有點更時髦......

要提取的文件名中的日期,使用

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

使這一切成爲地圖(使用文件名作爲鍵和日期值,雖然冗餘):

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 
+0

感謝您的答覆。想知道如何使用Groovy從文件名提取日期字符串 - 正則表達式: http://groovy.codehaus.org/Regular+Expressions 即input_02202010.xls - > 02202010 – firnnauriel 2010-02-24 09:21:39

+0

def s =「input_02222010.xls」 def s2 = s =〜/input_([d]]).xls/ assert「02222010」== s2 [0] [1] – 2010-02-24 18:52:31