Search code examples
scalafileutils

Scala : List the files which are greater than a file based on its name with timestamp pattern in it


I have to list out all files which are greater than particular file based on its timestamp in naming pattern in scala. Below is the example.

Files available:

log_20200601T123421.log
log_20200601T153432.log
log_20200705T093425.log
log_20200803T049383.log

Condition file:

log_20200601T123421.log - I need to list all the file names, which are greater than equal to 20200601T123421 in its name. The result would be,

Output list:

log_20200601T153432.log
log_20200705T093425.log
log_20200803T049383.log

How to achieve this in scala? I was trying with apache common, but i couldn't see greater than equal to NameFileFilter for it.


Solution

  • Perhaps the following code snippet could be a starting point:

    import java.io.File
    
    def getListOfFiles(dir: File):List[File] = dir.listFiles.filter(x => x.getName > "log_20200601T123421.log").toList
    
    val files = getListOfFiles(new File("/tmp"))
    

    For the extended task to collect files from different sub-directories:

    import java.io.File
    
    def recursiveListFiles(f: File): Array[File] = {
      val these = f.listFiles
      these ++ these.filter(_.isDirectory).flatMap(recursiveListFiles) 
    }
    
    val files = recursiveListFiles(new File("/tmp")).filter(x => x.getName > "log_20200601T123421.log")