Working
with files in Groovy is very easy. We have a lot of useful methods
available in the File
class. For example we can
run a Closure for each file that can be found in a directory with the eachFile()
method. Since Groovy 1.7.1
we can define if we only want to process the directories, files or
both. To do this we must pass a FileType
constant to the method. See
the following example code:
00.
import
groovy.io.FileType
01.
02.
//
First create sample dirs and files.
03.
(
1
..
3
).
each
{
04.
new
File(
"dir$it"
).mkdir()
05.
}
06.
(
1
..
3
).
each
{
07.
def
file
=
new
File(
"file$it"
)
08.
file
<<
"Sample
content for ${file.absolutePath}"
09.
}
10.
11.
def
currentDir
=
new
File(
'.'
)
12.
def
dirs
= []
13.
currentDir.
eachFile
FileType.DIRECTORIES,
{
14.
dirs
<< it.name
15.
}
16.
assert
'dir1,dir2,dir3'
==
dirs.
join
(
','
)
17.
18.
def
files
= []
19.
currentDir.
eachFile
(FileType.FILES)
{
20.
files
<< it.name
21.
}
22.
assert
'file1,file2,file3'
==
files.
join
(
','
)
23.
24.
def
found
= []
25.
currentDir.eachFileMatch(FileType.ANY,
~/.*
2
/)
{
26.
found
<< it.name
27.
}
28.
29.
assert
'dir2,file2'
==
found.
join
(
','
)