0

I want to use a java 8 DirectoryStream to find files that match a glob pattern, but I want to do it in Groovy (2.4 at least). I'm having trouble finding an example of how to do it though, since try-with-resources doesn't exist in groovy.

Additionally, what if the search pattern is **/*.txt. The pattern says it should cross directory boundaries, but my understanding of the DirectoryStream is that it doesn't.

def recent = {File file -> new Date() - new Date(file.lastModified) < 7}
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, job.pattern)) {
                    for (Path entry : stream) {
                            if(recent){
                                /*dostuff*/
                            }       
                        }
                    }
Steve
  • 4,457
  • 12
  • 48
  • 89
  • 1
    Can you show your not working code? – tim_yates Apr 17 '17 at 21:42
  • @tim_yates I've updated the question with the try-with-resources I couldn't get working. Basically we're operating on files modified in the last week that match a pattern – Steve Apr 18 '17 at 14:02

1 Answers1

1

The following does what you want (I think)

Files.newDirectoryStream(dir, { f -> f.fileName ==~ /.+\.txt/ }).withCloseable { stream ->
    stream.each {
        println it
    }
}

As you say, it doesn't recurse down in to directories

tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Right, but how can I go through directory boundaries if the file pattern requires it? Or should that be a separate question? – Steve Apr 18 '17 at 15:11
  • 1
    You could use AntBuilder? http://stackoverflow.com/questions/17206150/scan-directories-in-groovy-with-ant-builder-file-scanner `new AntBuilder().fileScanner { fileset(dir:dir) { include(name:'**/*.txt') } }.each { println it }` – tim_yates Apr 18 '17 at 15:29
  • I'm actually trying to get away from AntBuilder. I want to use nio Paths because then when I go to unit test, I can swap in an in-memory filesystem. I don't think that's possible with AntBuilder. It might be that there's no "easy" solution for what I want. – Steve Apr 18 '17 at 16:58
  • I've got a solution based on this, but Eclipse won't recognize withCloseable.I'm using groovy 2.4.3 – Steve Apr 18 '17 at 19:13
  • Files.walk(src, visitSubdirs).withCloseable{ Stream stream -> stream .filter{path -> filesystem.getPathMatcher("glob:${job.pattern}").matches(file.toPath())} .filter{job.days ? (new Date()) - new Date(file.lastModified()) <= job.days : true} .each{ actions[job.action](job, filePath.toFile()) fileCount++ } } – Steve Apr 18 '17 at 19:15
  • 1
    Eclipse is awful with groovy... Bet it works, but the IDE underlines it – tim_yates Apr 18 '17 at 19:16
  • 1
    Nice! Was just going to suggest Files.walk – tim_yates Apr 18 '17 at 19:41