File

Decompress a zip folder

With this example we are going to demonstrate how to decompress a zip folder in Java. In short, to decompress a zip folder 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.
  • Iterate over the ZipEntries of the ZipInputStream, using getNextEntry() method of ZipInputStream.
  • Create a new FileOutputStream using a path name with each entry name.
  • Create a BufferedOutputStream with the FileOutputStream using a byte array of specified length.
  • Read from the ZipInputStream, using its read(byte[] b, int off, int len) API method and write to the BufferedOutputStream 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.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DecompressZipFolder {

    //The path of the zipped folder e.g. C:/Users/nikos7/Desktop/lib.zip
    private static final String zippedFolderPath = "<ZIPPED FOLDER PATH>";
    
     //The path of the output folder e.g. C:/Users/nikos7/Desktop
    private static final String outputFolderPath = "<OUTPUT FOLDER PATH>";

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

  FileInputStream zippedFolder = new FileInputStream(zippedFolderPath);

  ZipInputStream zippedInputStream = new ZipInputStream(new BufferedInputStream(zippedFolder));

  ZipEntry entry;

  while ((entry = zippedInputStream.getNextEntry()) != null) {

System.out.println("Unzipping: " + entry.getName());

int size;

byte[] buffer = new byte[2048];

FileOutputStream fileOutputStream = new FileOutputStream(outputFolderPath+"/"+entry.getName());

BufferedOutputStream bufferedOutputsStream = new BufferedOutputStream(fileOutputStream, buffer.length);

while ((size = zippedInputStream.read(buffer, 0, buffer.length)) != -1) {

    bufferedOutputsStream.write(buffer, 0, size);
}
bufferedOutputsStream.flush();
bufferedOutputsStream.close();
  }
  zippedInputStream.close();
  zippedFolder.close();
    }
}

 
This was an example of how to decompress a zip folder in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button