8

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?

Community
  • 1
  • 1
Radek
  • 13,813
  • 52
  • 161
  • 255

2 Answers2

10

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$/}
cfrick
  • 35,203
  • 6
  • 56
  • 68
0
use 
 ^.*?.(?i)pdf

this will give only the first match

vks
  • 67,027
  • 10
  • 91
  • 124
  • `def p = ^.*?.(?i)pdf ` doesn't work for me. I am getting `org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:\createcontrol.txt: 15: unexpected token: ^ @ line 15, column 12.` – Radek Sep 03 '14 at 03:56
  • hm, it must be syntax issue. `def p = ^.*?.(?i)pdf` gives me the error. And `def p = /^.*?.(?i)pdf/` gives me empty output. – Radek Sep 03 '14 at 05:39
  • 1
    @Radek regex should be ~ /regex/ of this form.def p = ~/^.*?.(?i)pdf/ – vks Sep 03 '14 at 05:43
  • ok, syntax fixed. Thank you. But it gives me the same result. All pdf files. – Radek Sep 03 '14 at 05:47
  • @Radek can you give a sample input – vks Sep 03 '14 at 06:06
  • I updated code sample. Please create c:\tmp directory and place 2 or more pdf files and run the code. Mine reg exp and yours gives me the same result - all pdf files. – Radek Sep 03 '14 at 06:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60496/discussion-between-vks-and-radek). – vks Sep 03 '14 at 06:30
  • 1
    i doubt that this can be solved with the regexp, as the regexp is called for each file and does not cary over any state to the next check. – cfrick Sep 03 '14 at 08:42