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

5

109

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?

Kalliekallista answered 17/10, 2010 at 15:48 Comment(0)
R
246

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
}
Reedreedbird answered 17/10, 2010 at 18:30 Comment(9)
By default, groovy imports java.io but not groovy.io so to use FileType you must have explicitly import it.Victualer
For using FileType, make sure you use the right groovy version: "the class groovy.io.FileType was introduced in Groovy version 1.7.1." see: #6317873Laughter
This was displaying the folder names along with its path. Eg: /tmp/directory1 How to get the directory1 alone in the outputHaruspicy
weird..this gives the root path even if i preface it with a . It goes /./pathRenin
How can I list all folders on directory ?Robey
does file -> list << file works similar to list.add(it) or is there a difference?Peti
@R.Sluiter there is no differenceReedreedbird
This solved my problem: #41934610 by placing the code in the script section of a shared library.Byssus
there is no type File in jenkins goovyAubergine
O
30

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

Overplus answered 22/7, 2016 at 12:18 Comment(0)
D
6

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
}
Discouragement answered 28/4, 2016 at 18:11 Comment(4)
although this probably does not recurse through subdirectories. However: worked for my purposes for separating out proguard files and importing them all at once :)Discouragement
Unfortunately this does not answer the question "all the files in a directory (recursive)". It will only list the current directory and is misleading in the context.Emmert
fileTree recurses.Pejoration
FileTree does not include directories (not treating them as files).Representative
G
3

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
    }
}
Gereron answered 19/3, 2020 at 21:5 Comment(1)
Using the list was taken from the IDEA above. The problem with the above scripts is that they require to import groovy.io.FileType.FILES. gradle scripts don't like that. So I just made a method to look for the files that calls itself when a directory is found.Gereron
E
2

With Kotlin Gradle script one can do it like this:

// ...
val yamls = layout.files({
    file("src/main/resources/mixcr_presets").walk()
        .filter { it.extension == "yaml" }
        .toList()
})
// ...
Elyssa answered 16/10, 2022 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.