【问题标题】:Recursive listing of all files matching a certain filetype in Groovy在 Groovy 中递归列出与特定文件类型匹配的所有文件
【发布时间】:2011-04-09 09:29:02
【问题描述】:

我正在尝试递归地列出与 Groovy 中特定文件类型匹配的所有文件。 This example 几乎做到了。但是,它不会列出根文件夹中的文件。有没有办法修改它以列出根文件夹中的文件?或者,有其他方法吗?

【问题讨论】:

    标签: recursion groovy matching


    【解决方案1】:

    eachDirRecurse 替换为eachFileRecurse,它应该可以工作。

    【讨论】:

      【解决方案2】:

      groovy 2.4.7 版:

      new File(pathToFolder).traverse(type: groovy.io.FileType.FILES) { it ->
          println it
      }
      

      你也可以添加过滤器

      new File(parentPath).traverse(type: groovy.io.FileType.FILES, nameFilter: ~/patternRegex/) { it ->
          println it
      }
      

      【讨论】:

        【解决方案3】:
        // Define closure
        def result
        
        findTxtFileClos = {
        
                it.eachDir(findTxtFileClos);
                it.eachFileMatch(~/.*.txt/) {file ->
                        result += "${file.absolutePath}\n"
                }
            }
        
        // Apply closure
        findTxtFileClos(new File("."))
        
        println result
        

        【讨论】:

        • 您的 sn-p 会多次找到同一个文件。要使其工作,您将不得不使用 eachDirRecurse 代替,并且对于每个目录,使用 dir.eachFileMatch 来查找目录中的文件。检查我的解决方案以找到解决问题的另一种方法。
        【解决方案4】:

        这应该可以解决您的问题:

        import static groovy.io.FileType.FILES
        
        new File('.').eachFileRecurse(FILES) {
            if(it.name.endsWith('.groovy')) {
                println it
            }
        }
        

        eachFileRecurse 采用枚举 FileType 指定您只对文件感兴趣。剩下的问题很容易通过过滤文件名来解决。可能值得一提的是,eachFileRecurse 通常会在文件和文件夹上递归,而eachDirRecurse 只查找文件夹。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-11-10
          • 2011-02-26
          • 2013-06-24
          • 2013-07-22
          • 1970-01-01
          • 2011-04-01
          • 2022-11-18
          相关资源
          最近更新 更多