I need to obtain a list of directories within a specific folder, without including subdirectories.
For example, consider the following directory structure:
A/B/C
A/D/E
A/F
A/regular-file.txt
If I want to obtain a list of directories within directory A
, the output should be: [B, D, F]
.
I've come across this thread, but it only discusses recursive calls. Is there an elegant way to obtain a list of directories within a folder without recursion?
There is also this way:
new File("/A").listFiles({ f -> f.isDirectory() } as FileFilter)
Slightly more efficient as it should only create 1 array.
The Java File
object's listFiles
methods only return File
objects within the specified directory. There is no recursion into subfolders. It's equivalent to doing ls -a
on the command line.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter)
In the above method the closure is called for each child of the parent folder, and whatever returns true it returns that object. The as FileFilter
is to convert the Groovy closure syntax into an instance of FileFilter
so it can call the method in Java. Surrounding it with parentheses is necessary in this case (ie no Closure suffix parameter syntax) so the cast will be performed before it passes it to the listFiles
method.