Only my share

Java , Groovy and others

Closure make File Access so Easy in Groovy

with one comment

As we know in Groovy, Closure is a class that only contain a pieces of code. If you came from C/C++ Closure will be identical to function pointer, but Closure has more capability and better safety mechanism. In this article, I will show you how Closure support in groovy can make file access whether it is read or write operation so easy.

If you are a Java programmer, you will agree that this is very complex to do read or write to a File. There has to be a try-catch mechanism to catch all possible IO Exception that possibly occur in the code. In groovy, You can forget all of kind of messy mechanisms and you can only concentrate to what will you do with the file.

/*
* File Demo
*/
// writing some text to c:/mylovepoet.txt
file = new File(‘c:/mylovepoet.txt’)
file.write(“oh my darling”)

// append some text to the same file
file.append(‘oh my darling oh my darling\n’)
file.append(‘please. stay away\n’)

//Create new file and write to it using withWriter method and with closure argument
file2 = new File(‘c:/mylovepoet2.txt’)
file2.withWriter{
writer ->
writer << ‘oh my sweety\n’
writer <<  ‘please come to me’
}

// append some more text to the file using withWriter
file2.withWriterAppend{
writer ->
writer << ‘oh oh.. don\’t go’
}

// now we can read the content of the first file
file.eachLine {
line ->
println line

}

// now we will display all line started with ‘please’

print “\nLIne started with ‘please’:\n”
file.eachLine {
line ->
if(line =~ /^please/){
println line
}
}

We can make some raw conclution about File Access in groovy. It is more convenient and faster to create a code that access a file without any annoying error-handling mechanisms. All of error handling automatically handled by Groovy.

Written by adpjhype

January 5, 2009 at 4:41 pm

Posted in Groovy

Tagged with

One Response

Subscribe to comments with RSS.

  1. [...] Closure make File Access so Easy in Groovy « Aldry’s share about Java, Groovy and Grails – Closure is a class that only contain a pieces of code. If you came from C/C++ Closure will be identical to function pointer, but Closure has more capability and better safety mechanism. In this article, I will show you how Closure support in groovy can make file access whether it is read or write operation so easy. //Create new file and write to it using withWriter method and with closure argument file2 = new File(’c:/mylovepoet2.txt’) file2.withWriter{ writer -> writer << ‘oh my sweetyn’ writer << ‘please come to me’ } [...]


Leave a Reply