How to extract a zip file in Java?

Here is an example to explain How to decompress files from a ZIP file or How to extract a files and directories in a compressed zip archive.

package com.nourit.javaIO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.FileUtils;

public class FileDecompression {

  private static final String ZIP_FILE = "D:\\tmp\\NOURITFile.zip";
  private static final String DEST_FOLDER = "D:\\tmp\\outputzip";
  private static FileOutputStream fileOutputStream;

  public static void main(String[] args) {

    try {
       //Create DEST_FOLDER directory if not exists
      File folder = new File(DEST_FOLDER);
      if (!folder.exists()) {
        folder.mkdir();
      }

      // Get the zip file content
      ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(ZIP_FILE));
      // Get the zipped file list entry
      ZipEntry zipEntry = zipInputStream.getNextEntry();

      while (zipEntry != null) {

        String fileName = zipEntry.getName();
        File newFile = new File(DEST_FOLDER + File.separator + fileName);
        System.out.println("file unzip : " + newFile.getAbsoluteFile());

        //Create all new folders
        File newfolder = new File(newFile.getParent());
        newfolder.mkdirs();
        
        fileOutputStream = new FileOutputStream(newFile);
        byte[] data = FileUtils.readFileToByteArray(newFile);
        fileOutputStream.write(data, 0, data.length);
        zipEntry = zipInputStream.getNextEntry();
      }

      zipInputStream.closeEntry();
      zipInputStream.close();

      System.out.println(DEST_FOLDER+" Created, Operation successful!");

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

Output:

Decompression file  : D:\tmp\outputzip\NOUR-IT-Destination.txt
Decompression file  : D:\tmp\outputzip\NOUR-IT.txt
Decompression file  : D:\tmp\outputzip\nourit\nourit.sh
Decompression file  : D:\tmp\outputzip\nourit\temp-nourit-file-name7880135018657413764.tmp
Decompression file  : D:\tmp\outputzip\nourit-test-1.txt
Decompression file  : D:\tmp\outputzip\nourit-test-2.txt
Decompression file  : D:\tmp\outputzip\nourit-test-3.txt
Decompression file  : D:\tmp\outputzip\nourit1.txt
Decompression file  : D:\tmp\outputzip\temp-nourit-file-name7880135018657413763.tmp
D:\tmp\outputzip Created, Operation successful!

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*