How to download zip file, unzip, browse content and inspect files (bonus: parse json file)

Hey everyone,

Today we are going to see how you can download a zip file, unzip the contents, browse the contents and inspect any file. On top of that, for a more practical example, we are going to parse a json file and deserialise its content into a java object:

First you need 2 basic dependencies: Apache Commons Compress and Google Gson

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-compress</artifactId>
     <version>1.9</version>
</dependency>

Then it’s gonna be something as simple as:

public static void main(String args[]) throws IOException, ArchiveException, URISyntaxException {
     // dummy url
     URL url = new URL("https://www.test.com/myzip.zip");
     URLConnection connection = url.openConnection();
     InputStream urlInputStream = connection.getInputStream();
        
     // create a temp file so that you can work with ZipFile
     File tempZipFile = new File("tempZipFile.zip");
     FileUtils.copyInputStreamToFile(urlInputStream, tempZipFile);
        
     ZipFile zipFile = new ZipFile(tempZipFile);
        
     Gson gson = new Gson();
        
     for (Enumeration<ZipArchiveEntry> zipEntryEnum = zipFile.getEntries(); zipEntryEnum.hasMoreElements();) {
        ZipArchiveEntry zipEntry = zipEntryEnum.nextElement();
        String name = zipEntry.getName();
        if (name.contains("manifest.json")) {
           InputStreamReader isr = new InputStreamReader(zipFile.getInputStream(zipEntry), Charsets.UTF_8);
           JsonReader reader = new JsonReader(isr);
           ManifestJson manifestJson = gson.fromJson(reader, ManifestJson.class);
           System.out.println("manifest: " + manifestJson.toString());
        }
     }
     tempZipFile.delete();
 }

Is the code self explainable? If not, please, let me know if you have any questions or if I can make it clearer…

Have fun spreading joy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s