【问题标题】:How to break from groovy 'eachFileMatch()'如何摆脱 groovy 'eachFileMatch()'
【发布时间】:2014-10-27 10:55:40
【问题描述】:

我有一个列出目录中所有 pdf 文件的工作脚本。它按预期工作,但我实际上需要的只是第一个 pdf 文件的文件名。然后我想打破eachFileMatch(),因为目录中可能有数千个pdf文件。

我尝试在eachFileMatch().find 之后从这个Break from groovy each closure 答案中使用find,但没有工作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
        }

谁能告诉我怎么做?

【问题讨论】:

    标签: regex groovy


    【解决方案1】:

    你不能摆脱这些each{} 方法(例外会起作用,但那真的很脏)。如果您检查eachFileMatch 的代码,您会看到,它已经读取了整个list() 并对其进行了迭代。所以这里的一个选择是只使用常规的 JDK 方法并使用 find 返回第一个:

    // 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$/}
    

    【讨论】:

    • 美女!工作顺利。感谢您对这两种方法的解释。我需要第二个。很高兴知道这两个。
    • 你是认真的==,不是吗?
    【解决方案2】:
    use 
     ^.*?.(?i)pdf
    

    这只会给出第一个匹配项

    【讨论】:

    • def p = ^.*?.(?i)pdf 对我不起作用。我收到org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:\createcontrol.txt: 15: unexpected token: ^ @ line 15, column 12.
    • 嗯,一定是语法问题。 def p = ^.*?.(?i)pdf 给了我错误。 def p = /^.*?.(?i)pdf/ 给了我空的输出。
    • @Radek 正则表达式应该是 ~ /regex/ 的这种形式。def p = ~/^.*?.(?i)pdf/
    • 好的,语法已修复。谢谢你。但它给了我同样的结果。所有 pdf 文件。
    • 我怀疑这可以用正则表达式解决,因为每个文件都会调用正则表达式,并且不会将任何状态转移到下一次检查。
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 2014-01-28
    • 2013-10-31
    • 2020-10-19
    • 2019-12-01
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多