2010-10-17 92 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

相關問題