IO - pford68/groovy-examples GitHub Wiki
Reading Files
There are several ways to read files in Groovy.
Using the File.text property
First, you can simply get the text property of the file.
def file2 = new File('groovy2.txt')
// Using the text property:
file2.text = '''We can even use the text property of
a file to set a complete block of text at once.'''
Using A Writer instance
def file3 = new File('groovy3.txt')
// Using a writer object:
file3.withWriter('UTF-8') { writer ->
writer.write('We can also use writers to add contents.')
}
Reading Contents into An Array
def file1 = new File('groovy1.txt')
// Reading contents of files to an array:
def lines = file1.readLines()
assert 2 == lines.size()
assert 'Working with files the Groovy way is easy.' == lines[0]
// Or we read with the text property:
assert 'We can also use writers to add contents.' == file3.text
Using Reader
def file2 = new File('groovy2.txt')
// Or with a reader:
count = 0
file2.withReader { reader ->
while (line = reader.readLine()) {
switch (count) {
case 0:
assert 'We can even use the text property of' == line
break
case 1:
assert 'a file to set a complete block of text at once.' == line
break
}
count++
}
}
Using a Filter
def file1 = new File('groovy1.txt')
// We can also read contents with a filter:
sw = new StringWriter()
file1.filterLine(sw) { it =~ /Groovy/ }
assert 'Working with files the Groovy way is easy.\r\n' == sw.toString()
Retrieving Files
We can look for files in a directory with different methods. For a complete list, see the File GDK documentation.
files = []
new File('.').eachFileMatch(~/^groovy.*\.txt$/) { files << it.name }
assert ['groovy1.txt', 'groovy2.txt', groovy3.txt'] == files
Writing to Files
Appending Content
You can also get a File object (passing the path to the File constructor) and append text to it with a << operator:
// Using the leftShift operator:
new File('/Users/paford/Documents/test.txt') << 'See how easy it is to add text to a file.\n'
Overwriting Files
However, that method appends, what if you want to overwrite the file content completely?
Groovy provides a File.write() method that does that:
// Writing to the files with the write method:
def file1 = new File('groovy1.txt')
file1.write 'Working with files the Groovy way is easy.\n'