1

我有以下文件夹/文件。

A/B/C/D/giga.txt
A/BB/
A/CC/DD/fifa.jpg
A/ZZZ/1/a.txt
A/ZZZ/2/b.png
A/ZZZ/3/

如何在 Gradle/Groovy 中编码以仅删除空目录/子文件夹。即删除上述示例中的“A/BB”、“A/ZZZ/3”。真实案例有很多这样的文件夹。

我试过了

tasks.withType(Delete) { includeEmptyDirs = true } 

没用

tasks.withType(Delete) { includeEmptyDirs = false } 

没用

我不想使用 Gradle > call > Ant 方式,因为那是我最后的手段。此外,不要通过为每个空文件夹编写显式删除语句来删除每个空文件夹。

案例 2:如果我运行以下命令:

delete fileTree (dir: "A", include: "**/*.txt")

上面的 cmd 将删除文件夹 A 下的任何 .txt 文件及其下的任何子文件夹。现在,这将使“A/ZZZ/1”成为“空文件夹”的有效候选者,我也想删除它。

4

2 回答 2

3

使用FileTree 的 Javadoc,考虑以下删除“A”下的空目录。使用 Gradle 1.11:

task deleteEmptyDirs() {
    def emptyDirs = []

    fileTree (dir: "A").visit { def fileVisitDetails ->
        def file = fileVisitDetails.file

        if (file.isDirectory() && (file.list().length == 0)) {
            emptyDirs << file
        }
    }    

    emptyDirs.each { dir -> dir.delete() }
}
于 2014-03-06T05:12:40.080 回答
3

如果要删除所有本身仅包含空文件夹的文件夹,此代码可能会有所帮助。

    def emptyDirs = []

    project.fileTree(dir: destdir).visit { 
        def File f = it.file

        if (f.isDirectory() ) {
            def children = project.fileTree(f).filter { it.isFile() }.files
            if (children.size() == 0) {
                emptyDirs << f
            }
        }
    }

    // reverse so that we do the deepest folders first
    emptyDirs.reverseEach { it.delete() }
于 2015-11-04T01:36:45.680 回答