英文:
Is there a non-recursive method to obtain a list of directories within a specific folder in groovy?
问题
要获取特定文件夹中的目录列表,但不包括子目录,您可以使用以下方法:
import os
directory_path = 'A' # 将此路径替换为您要查找的文件夹路径
directories = [d for d in os.listdir(directory_path) if os.path.isdir(os.path.join(directory_path, d))]
print(directories)
这将返回目录A
中的所有目录名称,不包括子目录。在您的示例中,输出应为['B', 'D', 'F']
。
英文:
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?
答案1
得分: 2
这也有一种方法:
new File("/A").listFiles(f -> f.isDirectory())
这种方式稍微更有效,因为它只会创建一个数组。 Java中的File
对象的listFiles
方法只返回指定目录中的File
对象。它不会递归到子文件夹。这相当于在命令行上运行ls -a
。
在上述方法中,对于父文件夹的每个子文件,都会调用闭包,如果返回true,则返回该对象。as FileFilter
用于将Groovy闭包语法转换为FileFilter
的实例,以便在Java中调用该方法。在这种情况下,将其括在括号中是必要的(即没有Closure后缀参数语法),以便在将其传递给listFiles
方法之前执行强制转换。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论