2010-10-17 154 views
75

我试图获取(不打印,很容易)目录中的文件列表,它是子目录。获取目录中所有文件的列表(递归)

我已经试过:

def folder = "C:\\DevEnv\\Projects\\Generic"; 
def baseDir = new File(folder); 
files = baseDir.listFiles(); 

我只得到了迪尔斯。我也试过

def files = [];  

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

baseDir.eachFileRecurse(FileType.FILES, processFileClosure); 

但是在封闭范围内没有识别出“文件”。

如何获取列表?

回答

150

此代码的工作对我来说:

import groovy.io.FileType 

def list = [] 

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

之后列表变量包含指定目录下的所有文件(java.io.File中)及其子目录:

list.each { 
    println it.path 
} 
+11

默认情况下,常规的进口java.io而不是groovy.io所以要使用的文件类型,您必须明确地将其导入。 – 2013-06-28 07:04:03

+2

要使用FileType,请确保使用正确的groovy版本:“groovy.io.FileType类是在Groovy 1.7.1版中引入的。”请参阅:http://stackoverflow.com/questions/6317373/unable-to-resolve-class-groovy-io-filetype-error – 2014-09-29 12:36:55

+0

这显示文件夹名称及其路径。 例如:'/ tmp/directory1' 如何在输出 – 2017-03-12 04:50:33

5

如果这有助于其他任何人,下面的工作适用于我在Gradle/Groovy for build.gradle for Android项目,而不必导入groovy.io.FileType(注意:不递归子目录,但是当我发现这个解决方案时,我不再关心递归,所以你可能不会):

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

中单独获取'directory1',尽管这可能不会通过子目录递归。然而:为我的目的分离出proguard文件并一次性导入它们:) – ChrisPrime 2016-04-28 18:12:38

+0

不幸的是,这并没有回答“目录中的所有文件(递归)”的问题。它只会列出当前目录,并且在上下文中具有误导性。 – ottago 2016-06-04 06:28:13

+0

'fileTree'递归。 – 2017-08-24 16:56:26

相关问题