获取目录中所有文件的列表(递归)

Yos*_*ale 87 groovy file

我试图获取(不打印,这很容易)目录及其子目录中的文件列表.

我试过了:

def folder = "C:\\DevEnv\\Projects\\Generic";
def baseDir = new File(folder);
files = baseDir.listFiles();
Run Code Online (Sandbox Code Playgroud)

我只得到目录.我也尝试过:

def files = [];

def processFileClosure = {
        println "working on ${it.canonicalPath}: "
        files.add (it.canonicalPath);
    }

baseDir.eachFileRecurse(FileType.FILES, processFileClosure);
Run Code Online (Sandbox Code Playgroud)

但是在封闭范围内无法识别"文件".

我如何获得清单?

Chr*_*orf 200

这段代码适合我:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}
Run Code Online (Sandbox Code Playgroud)

然后list变量包含给定目录及其子目录的所有文件(java.io.File):

list.each {
  println it.path
}
Run Code Online (Sandbox Code Playgroud)

  • 默认情况下,groovy导入java.io但不导入groovy.io,因此要使用FileType,必须明确导入它. (14认同)
  • 要使用 FileType,请确保使用正确的 groovy 版本:“类 groovy.io.FileType 是在 Groovy 版本 1.7.1 中引入的。” 见:http://stackoverflow.com/questions/6317373/unable-to-resolve-class-groovy-io-filetype-error (3认同)

小智 12

较新版本的Groovy(1.7.2+)提供了JDK扩展,可以更轻松地遍历目录中的文件,例如:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
Run Code Online (Sandbox Code Playgroud)

有关更多示例,另请参见[1].

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html


Chr*_*ime 6

以下适用于我的Gradle/Groovy for build.gradleAndroid项目,无需导入groovy.io.FileType(注意:不会递归子目录,但是当我找到这个解决方案时,我不再关心递归,所以你可能也不会):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}
Run Code Online (Sandbox Code Playgroud)