Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Filtering Files/Directories



Groovy provides File class which represents a directory or File object and provides methods to filter a file or directory based on certain criteria.

Example - Filtering names of files/directories in directory

File.list(FilenameFilter filter) method returns an array of String objects where each string represent the name of the file or directory in the directory and are fulfiling the filter criteria. FilenameFilter is a Groovy closure/object of java.io.FilenameFilter class.

Example.groovy

// get the current directory
def currentDir = new File('.')
 
// get names of groovy files/directories within current directory
def groovyFiles = currentDir.list { dir, name -> name.endsWith('.groovy') }

println "\nGroovy files in '${currentDir.name}':"

// Use of safe navigation operator ?. avoids NullPointerException if no files found
groovyFiles?.each { println it }

Output

When we run the above program, we will get the following result.

Groovy files in '.':
Example.groovy

Example - Filtering File Objects of files/directories in directory

File.listFiles(FileFilter filter) method returns an array of File objects where each file object represent file or directory in the directory which satisfies the given filter. FileFilter is a Groovy closure/object of java.io.FileFilter class.

Example.groovy

// get the current directory
def currentDir = new File('.')
 
// get file objects for only subdirectories within current directory
def directories = currentDir.listFiles { it.isDirectory() } as File[] 

println "\nSubdirectories in '${currentDir.name}':"
directories?.each { println it.name }

Output

When we run the above program, we will get the following result.

Subdirectories in '.':
Test Directory
Advertisements