我有一个工作脚本,列出目录中的所有pdf文件.它按预期工作,但我需要的只是第一个pdf文件的文件名.然后我想打破,eachFileMatch()
因为目录中可能有数千个pdf文件.
我尝试使用find
从这个休息从groovy每个闭包答案之后,eachFileMatch().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
}
Run Code Online (Sandbox Code Playgroud)
谁能让我知道怎么做?
你不能打破这些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$/}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6533 次 |
最近记录: |