Groovy provides a number of {link:helper methods|http://groovy.codehaus.org/groovy-jdk.html}{link} for working with I/O. All of these work with standard Java Reader/Writer and InputStream/OutputStream and File and URL classes.Wiki Markup
The use of closures allows resources to be processed ensuring that things are properly closed irrespective of exceptions. e.g. to iterate through each line of a file the following can be used...
...
| Code Block |
|---|
def count=0, MAXSIZE=100
new File("foo.txt").withReader { reader ->
while (reader.readLine() != null) {
if (++count > MAXSIZE) throw new RuntimeException('File too large!')
}
}
|
and
| Code Block |
|---|
def fields = ["a":"1", "b":"2", "c":"3"]
new File("foo.ini").withWriter { out ->
fields.each() { key, value ->
out.writeLine("${key}=${value}")
}
}
|
...