[英]Groovy read most recent file in directory
我只是有一個關於編寫一個函數的問題,該函數將在目錄中搜索目錄中的最新日志。 我目前想出了一個,但我想知道是否有更好的(也許更合適的)這樣做的方式。
我目前正在使用hdsentinel在計算機上創建日志並將日志放在目錄中。 日志保存如下:
/directory/hdsentinel-computername-date
ie. C:/hdsentinel-owner-2010-11-11.txt
所以我編寫了一個快速腳本,循環訪問某些變量以檢查最近的(在過去一周內),但在查看之后,我會質疑以這種方式做事的效率和適當程度。
這是腳本:
String directoryPath = "D:"
def computerName = InetAddress.getLocalHost().hostName
def dateToday = new Date()
def dateToString = String.format('%tm-%<td-%<tY', dateToday)
def fileExtension = ".txt"
def theFile
for(int i = 0; i < 7; i++) {
dateToString = String.format('%tY-%<tm-%<td', dateToday.minus(i))
fileName = "$directoryPath\\hdsentinel-$computerName-$dateToString$fileExtension"
theFile = new File(fileName)
if(theFile.exists()) {
println fileName
break;
} else {
println "Couldn't find the file: " + fileName
}
}
theFile.eachLine { print it }
腳本運行正常,也許它有一些缺陷。 在我繼續之前,我覺得我應該繼續問一下這類事情的典型路線。
所有輸入都表示贊賞。
雖然有點混亂,但您可以通過'groupBy'方法實現多列排序(在Aaron的代碼上進行闡述)。
def today = new Date()
def recent = {file -> today - new Date(file.lastModified()) < 7}
new File('/yourDirectory/').listFiles().toList()
.findAll(recent)
.groupBy{it.name.split('-')[1]}
.collect{owner, logs -> logs.sort{a,b -> a.lastModified() <=> b.lastModified()} }
.flatten()
.each{ println "${new Date(it.lastModified())} ${it.name}" }
這將查找上周創建的所有日志,按所有者名稱對其進行分組,然后根據修改日期進行排序。
如果目錄中有日志以外的文件,則可能首先需要grep包含'hdsentinel'的文件。
我希望這有幫助。
編輯:從您提供的示例,我無法確定格式中的最低有效數字:
C:/hdsentinel-owner-2010-11-11.txt
表示月份或日期。 如果是后者,按文件名排序將自動按所有者划分優先級,然后按創建日期(不包含上述代碼的所有詭計)。
例如:
new File('/directory').listFiles().toList().findAll(recent).sort{it.name}
希望這有助於一些......這可以通過以更加時髦的方式修改日期對給定路徑進行排序。 將它們列出來。
您可以限制列表,並在閉包中添加其他條件以獲得所需的結果
new File('/').listFiles().sort() {
a,b -> a.lastModified().compareTo b.lastModified()
}.each {
println it.lastModified() + " " + it.name
}
當我試圖解決類似的問題時,學會了一種更清潔的方法。
定義用於排序的閉包
def fileSortCondition = { it.lastModified() }
File.listFiles()有其他變體,它接受Java中的FileFilter和FilenameFilter,這些接口有一個名為accept的方法,將接口實現為閉包。
def fileNameFilter = { dir, filename ->
if(filename.matches(regrx))
return true
else
return false
} as FilenameFilter
最后
new File("C:\\Log_Dir").listFiles(fileNameFilter).sort(fileSortCondition).reverse()
如果要通過File屬性進行過濾,請實現FileFilter接口。
def fileFilter = { file ->
if(file.isDirectory())
return false
else
return true } as FileFilter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.