Groovy為I/O提供了一系列的helper methods ,所有的這些方法都適用於標准的 Java Reader/Writer ,InputStream/OutputStream 和File 以及URL classes.
閉包的使用可以確保資源被正確的關閉,比如遍歷文件的每一行可以使用下面的代碼:
1 |
new File("foo.txt").eachLine { line -> println(line) } |
如果在某些情況下,println()方法拋出了異常,那么eachLine()方法將確保資源被正確的關閉,同樣的,如果在讀取的時候發生了異常,那么資源也將會被正確的關閉。
如果你希望使用在reader/writer object或者input/output stream object的時候,有一些輔助方法來幫助你處理資源的關閉,那么這個時候你可以使用閉包。他將自動的在異常發生的時候關閉所有的資源,比如下面的代碼:
1 |
def count=0, MAXSIZE=100 |
2 |
new File("foo.txt").withReader { reader -> |
3 |
while (reader.readLine() != null) { |
4 |
if (++count > MAXSIZE) throw new RuntimeException('File too large!') |
以及:
1 |
def fields = ["a":"1", "b":"2", "c":"3"] |
2 |
new File("foo.ini").withWriter { out -> |
3 |
fields.each() { key, value -> |
4 |
out.writeLine("${key}=${value}") |
Further Information