Get a list of all the files in a directory (recursive)

FileGroovyDirectory Listing

File Problem Overview


I'm trying to get (not print, that's easy) the list of files in a directory and its sub directories.

I've tried:

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

I only get the directories. I've also tried:

def files = [];

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

baseDir.eachFileRecurse(FileType.FILES, processFileClosure);

But "files" is not recognized in the scope of the closure.

How do I get the list?

File Solutions


Solution 1 - File

This code works for me:

import groovy.io.FileType

def list = []

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

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

Solution 2 - File

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

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

See also [1] for more examples.

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

Solution 3 - File

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

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

Solution 4 - File

This is what I came up with for a gradle build script:

task doLast {
	ext.FindFile = { list, curPath ->
		def files = file(curPath).listFiles().sort()
		
		files.each {  File file ->
			
			if (file.isFile()) {
				list << file
			}
			else {
				list << file  // If you want the directories in the list
				
				list = FindFile( list, file.path) 
			}
		}
		return list
	}
	
	def list = []
	def theFile = FindFile(list, "${project.projectDir}")
	
	list.each {
		println it.path
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYossaleView Question on Stackoverflow
Solution 1 - FileChristoph MetzendorfView Answer on Stackoverflow
Solution 2 - FileOscar ScholtenView Answer on Stackoverflow
Solution 3 - FileChrisPrimeView Answer on Stackoverflow
Solution 4 - FileTimothy StrunkView Answer on Stackoverflow