Groovy读取目录中的最新文件

Sta*_*ovy 2 directory groovy file

我只是有一个关于编写一个函数的问题,该函数将在目录中搜索目录中的最新日志.我目前想出了一个,但我想知道是否有更好的(也许更合适的)这样做的方式.

我目前正在使用hdsentinel在计算机上创建日志并将日志放在目录中.日志保存如下:

/directory/hdsentinel-computername-date

ie. C:/hdsentinel-owner-2010-11-11.txt
Run Code Online (Sandbox Code Playgroud)

所以我编写了一个快速脚本,循环访问某些变量以检查最近的(在过去一周内),但在查看之后,我会质疑以这种方式做事的效率和适当程度.

这是脚本:

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 }
Run Code Online (Sandbox Code Playgroud)

脚本运行正常,也许它有一些缺陷.在我继续之前,我觉得我应该继续问一下这类事情的典型路线.

所有输入都表示赞赏.

Nor*_*ver 5

虽然有点乱,但你可以通过'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}" } 
Run Code Online (Sandbox Code Playgroud)

这将查找上周创建的所有日志,按所有者名称对其进行分组,然后根据修改日期进行排序.

如果目录中有日志以外的文件,则可能首先需要grep包含'hdsentinel'的文件.

我希望这有帮助.

编辑: 从您提供的示例,我无法确定格式中的最低有效数字:

C:/hdsentinel-owner-2010-11-11.txt

表示月份或日期.如果是后者,按文件名排序将自动按所有者划分优先级,然后按创建日期(不包含上述代码的所有诡计).

例如:

new File('/directory').listFiles().toList().findAll(recent).sort{it.name}
Run Code Online (Sandbox Code Playgroud)