Search

Dark theme | Light theme

April 27, 2010

Groovy Goodness: Working on Files or Directories (or Both) with FileType

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:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import groovy.io.FileType
 
// First create sample dirs and files.
(1..3).each {
 new File("dir$it").mkdir()
}
(1..3).each {
 def file = new File("file$it")
 file << "Sample content for ${file.absolutePath}"
}
 
def currentDir = new File('.')
def dirs = []
currentDir.eachFile FileType.DIRECTORIES, {
    dirs << it.name
}
assert 'dir1,dir2,dir3' == dirs.join(',')
 
def files = []
currentDir.eachFile(FileType.FILES) {
    files << it.name
}
assert 'file1,file2,file3' == files.join(',')
 
def found = []
currentDir.eachFileMatch(FileType.ANY, ~/.*2/) {
   found << it.name
}
 
assert 'dir2,file2' == found.join(',')