Sunday, January 13, 2019

How to Unzip in Java

Here is a quick java program to unzip or explode a zip file. We will read the zip file with the help of java.util.ZipFile, then we will process each entries inside this. We will read the entries as stream and write to a buffer and eventually to a file output stream.  So at the end we will extract all the elements in the zip, and maintain the same hierarchical structure of directories .Please refer the below example.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnZipDemo {
public static void main(String args[]) throws IOException
{
String zipFileName = "D:\\demo.zip";
ZipFile zipFile = new ZipFile(zipFileName);
String extractedPath = "D:\\demo";
byte[] buffer = new byte[1024];
Enumeration enm = zipFile.entries();
ZipEntry ze = null;
InputStream fis = null;
while (enm.hasMoreElements()) {
ze = (ZipEntry) enm.nextElement();
System.out.println("processing = "+ze.getName());
File newFile = new File(extractedPath + File.separator + ze.getName());
// create all non exists folders
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
fis = zipFile.getInputStream(ze);
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
}

1 comment:

  1. Thanks for the code, this is code looks much similar to C#.

    https://corevoila.in/question/how-to-create-rar-file-in-c-net/

    ReplyDelete

Thanks.