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?
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
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.
You can print the current value of a variable with the println function.
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$/}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With