
In the previous example we have seen “How to compress files/folder in java“. Now we will focus on “Java Utility to Decompress a Zip File In Java”
Java provides “java.util.zip” library to compress files/folder in zip format.
Steps to follow –
1. Take folder/files path as input.
2. Read the zip file using ZipInputStream
3. Get the zip file list entry ZipEntry, and output it using “FileOutputStream”.
package com.jkoder;
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;
public class UnzipFolderExample {
private final static String OUTPUt_FOLDER_NAME = "/opt/dev/report/";
private final static String ZIP_FILE_NAME = "/opt/dev/report.zip";
public static void main(String[] args) {
byte[] buffer = new byte[1024];
try {
// check if output folder exist, if not create it
File outputFolder = new File(OUTPUt_FOLDER_NAME);
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
ZipInputStream zipfile = new ZipInputStream(new FileInputStream(
ZIP_FILE_NAME));
ZipEntry zipentry = zipfile.getNextEntry();
while (zipentry != null) {
String fileName = zipentry.getName();
File newFile = new File(outputFolder + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zipfile.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
zipentry = zipfile.getNextEntry();
}
zipfile.closeEntry();
zipfile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Jkoder.com Tutorials, Tips and interview questions for Java, J2EE, Android, Spring, Hibernate, Javascript and other languages for software developers