Home » Core Java » io » File » Extract a compressed zip file

About Byron Kiourtzoglou

Byron Kiourtzoglou
Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Extract a compressed zip file

This is an example of how to extract a compressed zip file. Extracting a compressed zip file implies that you should:

  • Create a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
  • Create a new ZipInputStream.
  • Create a new FileOutputStream using a path name to the file to write.
  • Iterate over the ZipEntries of the ZipInputStream, using getNextEntry() method of ZipInputStream.
  • Read from the ZipInputStream, using its read(byte[] b, int off, int len) API method and write to the FileOutputStream with write(byte[] b, int off, int len) API method.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ExtractZipFile {

    //Zipped file path e.g. C:/Users/nikos7/comperssed.zio
    private static final String zippedFilePath="<ZIPPED FILE PATH>"; 
        
    private static final String outputFilePath="<OUTPUT FILE PATH>"; 

    public static void main(String[] args) throws Exception {

  ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zippedFilePath));

  OutputStream outputStream = new FileOutputStream(outputFilePath);

  byte[] buf = new byte[1024];

  int read;

  ZipEntry zipEntry;

  if ((zipEntry = inputStream.getNextEntry()) != null) {

while ((read = inputStream.read(buf)) > 0) {
    outputStream.write(buf, 0, read);
}

  }
  outputStream.close();
  inputStream.close();
    }
}

 
This was an example of how to extract a compressed zip file in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of