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.
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.
Let's assume we have a ZIP file named archive.zip
containing a bunch of text files.
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'))
a/b.txt This is text file! c/d.txt This is another text file!
The dumpZipContent
function takes a File
as an argument and creates a JDK ZipFIle
out of it. Finally, the code iterates on all the entries of the ZIP file, filtering out the folders. The iteration is done through a couple of nested closures, the second of which prints the content of the ZIP file using the handy text
property added to the Java's InputStream
class by Groovy JDK.
We have already encountered the AntBuilder
class in the Deleting a file or directory recipe. This class is a gateway to the enormous amount of tasks exposed by the Ant build system. Among them, we can find the unzip task that allows us to decompress a ZIP
, JAR
, WAR
, and EAR
file:
def ant = new AntBuilder() ant.unzip (src: 'zipped.zip', dest: '.')
The previous snippet unzips a file named zipped.zip
into the same folder where the code is executed. For a complete list of properties of the unzip task, refer to Ant documentation (https://ant.apache.org/manual/Tasks/unzip.html).
18.222.168.163