File

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.

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button