You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy技术问询:检查目录文件、筛选含h文件名及代码修正

Groovy 文件操作问题解答

一、检查目录是否包含指定文件

  • 仅检查目录直接子文件:

    def doesFileExistInDir(String dirPath, String targetFileName) {
        def targetFile = new File(dirPath, targetFileName)
        // 确保是文件而非目录
        return targetFile.exists() && targetFile.isFile()
    }
    
    // 调用示例
    def exists = doesFileExistInDir("/path/to/directory", "test.txt")
    println "文件是否存在:${exists}"
    
  • 递归检查所有子目录:

    def doesFileExistRecursively(String dirPath, String targetFileName) {
        def found = false
        new File(dirPath).eachFileRecurse { file ->
            if (file.name == targetFileName && file.isFile()) {
                found = true
                // 找到后终止递归,提升效率
                return false
            }
        }
        return found
    }
    

二、筛选文件名包含字母"h"的文件列表

针对大量文件场景,推荐用高效的集合筛选方式:

def getFilesWithHInName(String dirPath) {
    def dir = new File(dirPath)
    // 仅筛选文件(排除目录),且文件名包含"h"(区分大小写)
    return dir.listFiles().findAll { it.isFile() && it.name.contains('h') }.collect { it.name }
}

// 调用示例
def fileList = getFilesWithHInName("/path/to/large-directory")
fileList.each { println it }

如果需要不区分大小写匹配"h"或"H":

return dir.listFiles().findAll { it.isFile() && it.name.toLowerCase().contains('h') }.collect { it.name }

三、问题代码修正

原代码存在这些问题:

  1. 变量名错误:fileWithModulesH未定义,实际应为fileLabel
  2. 多余的>符号属于格式错误
  3. 未判断遍历对象是否为文件(会误处理目录)
  4. 用List.contains()去重效率低,大文件场景建议用Set自动去重

修正后的代码:

def findFilesWithModulesH(def steps, def target) {
    // 用HashSet自动去重,比List的contains检查更高效
    def filesWithModulesH = new HashSet<>()
    new File(target).eachFile { file ->
        // 仅处理文件,排除目录
        if (file.isFile()) {
            steps.println "AAAAAAAAAAAAAAAA0 ${file}"
            def fileLabel = file.name.tokenize("-")[0].toUpperCase()
            filesWithModulesH.add(fileLabel)
        }
    }
    // 转成List返回(如果业务需要List类型)
    return filesWithModulesH.toList()
}

若必须保留List去重逻辑,可修改为:

def findFilesWithModulesH(def steps, def target) {
    def filesWithModulesH = []
    new File(target).eachFile { file ->
        if (file.isFile()) {
            steps.println "AAAAAAAAAAAAAAAA0 ${file}"
            def fileLabel = file.name.tokenize("-")[0].toUpperCase()
            if (!filesWithModulesH.contains(fileLabel)) {
                filesWithModulesH.add(fileLabel)
            }
        }
    }
    return filesWithModulesH
}

内容的提问来源于stack exchange,提问作者rhoudri hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:13:27