Groovy_遍历文件目录

时间:2025-03-22 17:50:25

Official documentation: /latest/html/groovy-jdk/java/io/

Common method:

1. void eachDir(Closure closure): Invokes the closure for each subdirectory in this directory, ignoring regular files.

class eachDirTest {
        public static void main(String[] args) {
            def count = 0
            def dir = new File("D:\\Project\\SoapUI\\Project-smoke-tests")

            {directory->
                println directory
            }
        }  
} 

2. void eachDirMatch(Object nameFilter, Closure closure): Invokes the closure for each subdirectory whose name () matches the given nameFilter in the given directory - calling the DefaultGroovyMethods#isCase(, method to determine if a match occurs.

class eachDirTest {
    public static void main(String[] args) {
        def count = 0
        def dir = new File("D:\\Project\\SoapUI\\Project-smoke-tests")

        (~/^Sanity.*/){d ->
            println d
        }
    } 
}

Output:
D:\Project\SoapUI\Project-smoke-tests\SanityTestSuite1
D:\Project\SoapUI\Project-smoke-tests\SanityTestSuite2
D:\Project\SoapUI\Project-smoke-tests\SanityTestSuite3
D:\Project\SoapUI\Project-smoke-tests\SanityTestSuite4
D:\Project\SoapUI\Project-smoke-tests\SanityTestSuite5
……..

3. eachDirRecurse(File self, Closure closure) : Invokes the closure for each descendant directory of this directory.

class eachDirTest {
        public static void main(String[] args) {
            def count = 0
            def dir = new File("D:\\Project\\SoapUI\\Project-smoke-tests")

            {directory->
                println directory
            }
        }  
}