Regex – How to break from groovy ‘eachFileMatch()’

groovyregex

I have a working script that lists all pdf files in a directory. It's working as desired but all I need is actually the file name of the first pdf file. Then I want to break the eachFileMatch() as there could be thousands of pdf files in the directory.

I tried to use find from this Break from groovy each closure answer after eachFileMatch().find but didn't work Caught: groovy.lang.MissingMethodException: No signature of method: java.io.File.eachFileMatch() is applicable for argument types: (java.util.regex.Pattern) values: [.*.(?i)pdf]

        def directory="c:\\tmp"   // place 2 or more pdf files in that
                                  // directory and run the script
        def p =  ~/.*.(?i)pdf/
        new File( directory ).eachFileMatch(p) { pdf ->
                println pdf // and break
        }

Could anyone give me an idea how to do so?

Best Answer

you can not break out of these each{} methods (exceptions will work, but that would be really dirty). if you check the code for eachFileMatch, you see, that it already reads the whole list() and itereates over it. so one option here is to just use the regular JDK methods and use find to return the first:

// only deal with filenames as string
println new File('/tmp').list().find{it=~/.tmp$/}

// work with `File` objects
println new File('/tmp').listFiles().find{it.isFile() && it=~/.tmp$/}