Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break from groovy 'eachFileMatch()'

Tags:

regex

groovy

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?

like image 658
Radek Avatar asked Sep 03 '14 03:09

Radek


People also ask

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I use regular expression in groovy script?

A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.

How do I print a value in groovy script?

You can print the current value of a variable with the println function.


1 Answers

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$/}
like image 50
cfrick Avatar answered Sep 28 '22 07:09

cfrick