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.

  1. 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'))
  2. 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 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.

There's more...

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).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.35.72