Archive for the ‘Groovy’ category

Groovy Code Sample

February 21st, 2010

For my latest project ProboGen, I needed the functionality to create and zip files. I found this this groovy code and show its show how powerfull groovy is.


File.metaClass.zip = { String destination ->
def result = new ZipOutputStream(new FileOutputStream(destination))
result.withStream {zipOutStream->
delegate.eachFileRecurse { f ->
if(!f.isDirectory()) {
zipOutStream.putNextEntry(new ZipEntry(f.getPath()))
new FileInputStream(f).withStream { inStream ->
def buffer = new byte[1024]
def count
while((count = inStream.read(buffer, 0, 1024)) != -1) {
zipOutStream.write(buffer)
}
}
zipOutStream.closeEntry()
}
}
}
}

To zip up a directory you can now just say:


new File("/data/ft/").zip("/ft.zip");

This is really neat solution.

Thanks to : powerful groovy