Reading data from a ZIP file
Reading from a ZIP file with Groovy is a simple affair. This recipe shows you how to read the contents of a ZIP file without having to extract the content first.
Getting ready
Groovy doesn't have any GDK class to deal with ZIP files so we have to approach the problem by using one of the JDK alternatives. Nevertheless, we can "groovify" the code quite a lot in order to achieve simplicity and elegance.
How to do it...
Let's assume we have a ZIP file named archive.zip
containing a bunch of text files.
The following code iterates through the ZIP entries and prints the name of the file as well as the content:
def dumpZipContent(File zipFIle) { def zf = new java.util.zip.ZipFile(zipFIle) zf.entries().findAll { !it.directory }.each { println it.name println zf.getInputStream(it).text } } dumpZipContent(new File('archive.zip'))
The output may look as follows:
a/b.txt This is text file! c/d.txt This is another text file!
How it works...
The dumpZipContent
function...