获取目录中所有文件的列表(递归)
我正在尝试获取(不是打印,这很容易)目录及其子目录中的文件列表。
我尝试过:
def folder = "C:\\DevEnv\\Projects\\Generic";
def baseDir = new File(folder);
files = baseDir.listFiles();
我只获取目录。我也尝试过:
def files = [];
def processFileClosure = {
println "working on ${it.canonicalPath}: "
files.add (it.canonicalPath);
}
baseDir.eachFileRecurse(FileType.FILES, processFileClosure);
但是“文件”在闭包范围内未被识别。
我如何获取列表?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
此代码对我有用:
之后列表变量包含给定目录及其子目录的所有文件(java.io.File):
This code works for me:
Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:
较新版本的 Groovy (1.7.2+) 提供了 JDK 扩展,可以更轻松地遍历目录中的文件,例如:
另请参阅 [1] 了解更多示例。
[1] http://mrhaki.blogspot.nl/2010/ 04/groovy-goodness-traversing-directory.html
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
以下内容适用于 Android 项目的 Gradle / Groovy for
build.gradle
,而无需导入groovy.io.FileType
(注意:不会递归子目录,但当我找到这个解决方案时,我不再关心递归,所以你也可能不关心):The following works for me in Gradle / Groovy for
build.gradle
for an Android project, without having to importgroovy.io.FileType
(NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):这是我为 gradle 构建脚本想到的:
This is what I came up with for a gradle build script:
使用 Kotlin Gradle 脚本,可以这样做:
With Kotlin Gradle script one can do it like this: