Search code examples
javagetzipunzip

Extract contents of Zip file downloaded using a HTTP GET request


I have to download a Zip file, from rest call and extract its contents (some PDF files and a PNG file).

I'm using Java Spring.

How can do it?


Solution

  • You can use Spring's RestTemplate to download the file

    RestTemplate templ = new RestTemplate();
    byte[] downloadedBytes = templ.getForObject(url, byte[].class);
    

    Extract the contents with standard java or a third party library.

    Example utility, adapted from here: http://www.codejava.net/java-se/file-io/programmatically-extract-a-zip-file-using-java

    package com.test;
    
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    
    public class ZipHelper {
    
        private static final int BUFFER_SIZE = 4096;
    
        public static void unzip(byte[] data, String dirName) throws IOException {
            File destDir = new File(dirName);
            if (!destDir.exists()) {
                destDir.mkdir();
            }
            ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(data));
            ZipEntry entry = zipIn.getNextEntry();
    
            while (entry != null) {
                String filePath = dirName + File.separator + entry.getName();
                if (!entry.isDirectory()) {
                    // if the entry is a file, extracts it
                    extractFile(zipIn, filePath);
                } else {
                    // if the entry is a directory, make the directory
                    File dir = new File(filePath);
                    dir.mkdir();
                }
                zipIn.closeEntry();
                entry = zipIn.getNextEntry();
            }
            zipIn.close();
        }
    
        private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] bytesIn = new byte[BUFFER_SIZE];
            int read = 0;
            while ((read = zipIn.read(bytesIn)) != -1) {
                bos.write(bytesIn, 0, read);
            }
            bos.close();
        }
    }
    

    Then you use this utility like so:

    ZipHelper.unzip(downloadedBytes, "/path/to/directory");