简体   繁体   English

Groovy读取目录中的最新文件

[英]Groovy read most recent file in directory

I just have a question about writing a function that will search a directory for the most recent log in a directory. 我只是有一个关于编写一个函数的问题,该函数将在目录中搜索目录中的最新日志。 I currently came up with one, but I'm wondering if there is a better (perhaps more proper) way of doing this. 我目前想出了一个,但我想知道是否有更好的(也许更合适的)这样做的方式。

I'm currently using hdsentinel to create logs on computer and placing the log in a directory. 我目前正在使用hdsentinel在计算机上创建日志并将日志放在目录中。 The logs are saved like so: 日志保存如下:

/directory/hdsentinel-computername-date

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

So I wrote a quick script that loops through certain variables to check for the most recent (within the past week) but after looking at it, I'm question how efficient and proper it is to do things this way. 所以我编写了一个快速脚本,循环访问某些变量以检查最近的(在过去一周内),但在查看之后,我会质疑以这种方式做事的效率和适当程度。

Here is the script: 这是脚本:

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 }

The script works fine, perhaps it has some flaws. 脚本运行正常,也许它有一些缺陷。 I felt I should go ahead and ask what the typical route is for this type of thing before I continue with it. 在我继续之前,我觉得我应该继续问一下这类事情的典型路线。

All input is appreciated. 所有输入都表示赞赏。

Though a bit messy, you could implement a multi-column sort via the 'groupBy' method (Expounding on Aaron's code).. 虽然有点混乱,但您可以通过'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}" } 

This finds all logs created within the last week, groups them by owner name, and then sorts according to date modified. 这将查找上周创建的所有日志,按所有者名称对其进行分组,然后根据修改日期进行排序。

If you have files other than logs in the directory, you may first need to grep for files containing 'hdsentinel.' 如果目录中有日志以外的文件,则可能首先需要grep包含'hdsentinel'的文件。

I hope this helps. 我希望这有帮助。

EDIT: From the example you provided, I cannot determine if the least significant digit in the format: 编辑:从您提供的示例,我无法确定格式中的最低有效数字:

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

represents the month or the day. 表示月份或日期。 If the latter, sorting by file name would automatically prioritize by owner, and then by date created (without all of the chicanery of the above code). 如果是后者,按文件名排序将自动按所有者划分优先级,然后按创建日期(不包含上述代码的所有诡计)。

For Instance: 例如:

new File('/directory').listFiles().toList().findAll(recent).sort{it.name}

Hopefully this helps some..This sorts a given path by date modified in a groovier way. 希望这有助于一些......这可以通过以更加时髦的方式修改日期对给定路径进行排序。 The lists them out. 将它们列出来。

you can limit the list, and add other conditions in the closure to get the desired results 您可以限制列表,并在闭包中添加其他条件以获得所需的结果

 new File('/').listFiles().sort() {
   a,b -> a.lastModified().compareTo b.lastModified()
 }.each {
     println  it.lastModified() + "  " + it.name
 } 

As I was trying to solve a similar problem, learnt a much cleaner approach. 当我试图解决类似的问题时,学会了一种更清洁的方法。

Define a closure for sorting 定义用于排序的闭包

def fileSortCondition = { it.lastModified() }

And File.listFiles() has other variation which accepts FileFilter and FilenameFilter in Java, and these interfaces has a single method called accept, Implement the interface as a closure. File.listFiles()有其他变体,它接受Java中的FileFilter和FilenameFilter,这些接口有一个名为accept的方法,将接口实现为闭包。

def fileNameFilter = { dir, filename ->
if(filename.matches(regrx))
    return true
else
    return false
} as FilenameFilter

And lastly 最后

new File("C:\\Log_Dir").listFiles(fileNameFilter).sort(fileSortCondition).reverse()

Implement FileFilter interface if filtering is to be done by File attributes. 如果要通过File属性进行过滤,请实现FileFilter接口。

def fileFilter = {  file ->
        if(file.isDirectory())
             return false 
        else
            return true }  as FileFilter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM