Groovy
adds the traverse()
method to the File
class in version 1.7.2. We
can use this method to traverse a directory tree and invoke a closure
to process the files and directories. If we look at the documentation
we see we can also pass a map with a lot of possible options to
influence the processing.
00.
import
static
groovy.io.FileType.*
01.
import
static
groovy.io.FileVisitResult.*
02.
03.
def
groovySrcDir
=
new
File(System.env[
'GROOVY_HOME'
],
'src/'
)
04.
05.
def
countFilesAndDirs
=
0
06.
groovySrcDir.traverse
{
07.
countFilesAndDirs++
08.
}
09.
println
"Total
files and directories in ${groovySrcDir.name}: $countFilesAndDirs"
10.
11.
def
totalFileSize
=
0
12.
def
groovyFileCount
=
0
13.
def
sumFileSize
= {
14.
totalFileSize
+= it.
size
()
15.
groovyFileCount++
16.
}
17.
def
filterGroovyFiles
= ~/.*\.groovy$/
18.
groovySrcDir.traverse
type: FILES, visit: sumFileSize, nameFilter: filterGroovyFiles
19.
println
"Total
file size for $groovyFileCount Groovy source files is: $totalFileSize"
20.
21.
def
countSmallFiles
=
0
22.
def
postDirVisitor
= {
23.
if
(countSmallFiles
>
0
)
{
24.
println
"Found
$countSmallFiles files with small filenames in ${it.name}"
25.
}
26.
countSmallFiles
=
0
27.
}
28.
groovySrcDir.traverse(type:
FILES, postDir: postDirVisitor, nameFilter: ~/.*\.groovy$/) {
29.
if
(it.name.
size
()
<
15
)
{
30.
countSmallFiles++
31.
}