有没有一种非递归的方法来获取Groovy中特定文件夹内的目录列表?

huangapple go评论55阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月26日 19:14:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571601.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定